我有返回SecIdentityRef
的objc函数
+ (SecIdentityRef)getSecIdentity {
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"cert1" ofType:@"p12"];
NSData *p12Data = [NSData dataWithContentsOfFile:resourcePath];
NSMutableDictionary * options = [[NSMutableDictionary alloc] init];
[options setObject:@"123456" forKey:(id)kSecImportExportPassphrase];
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
OSStatus securityError = SecPKCS12Import((CFDataRef) p12Data,
(CFDictionaryRef)options, &items);
if (securityError == noErr && CFArrayGetCount(items) > 0) {
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
SecIdentityRef identityApp =
(SecIdentityRef)CFDictionaryGetValue(identityDict,
kSecImportItemIdentity);
CFRelease(items);
return identityApp;
}
CFRelease(items);
return NULL;
}
我在桥接头中使用此函数导入类,然后在快速代码中使用它。
let test = Certificate.getSecIdentity()
let secIdentity = test.takeUnretainedValue()
从Certificate.getSecIdentity()
返回正确的Unmanaged<SecIdentityRef>
(?)SecIdentity在里面。
在test.takeUnretainedValue()
(和test.takeRetainedValue()
)上,我接收Thread 1: EXC_BAD_ACCESS (code=1, address=0x2d13e474f3e0)
我做错了什么?我怎样才能得到SecIdentity?
发布于 2022-09-23 06:25:21
当您从(我相信)任何核心基础集合中检索元素时,集合函数遵循得到-规则。这意味着在显式保留元素之前,您不会拥有它。因此,在代码的这一部分中:
(SecIdentityRef)CFDictionaryGetValue(identityDict,SecIdentityRef identityApp = kSecImportItemIdentity);CFRelease(项目);
本质上,您同时发布了items
和identityApp
,并返回了一个悬空指针(准确地说,是一个悬挂的核心基础引用)。只需在发布SecIdentityRef
数组之前保留items
实例,如下所示:
CFRetain(identityApp);
CFRelease(items);
return identityApp;
P.S.,因为您的函数可能返回NULL
,所以最好生成结果nullable
,特别是在使用Swift时,因此它知道结果是一个可选值:
+ (nullable SecIdentityRef)getSecIdentity
P.P.S.您可能还想直接用Swift重写代码,因为SecCertificate
https://stackoverflow.com/questions/73813809
复制相似问题