我有 objc 函式回傳SecIdentityRef
(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?
uj5u.com熱心網友回復:
當您從(我相信)任何核心基礎集合中檢索元素時,集合函式遵循Get-Rule。這意味著您不擁有該元素,直到您明確保留它。因此,在這部分代碼中:
SecIdentityRef identityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity); CFRelease(items);
您基本上釋放items并identityApp回傳一個懸空指標(準確地說是一個懸空的核心基礎參考)。SecIdentityRef只需在發布陣列之前保留實體,items如下所示:
CFRetain(identityApp);
CFRelease(items);
return identityApp;
PS,因為你的函式可能會回傳NULL,你最好做出 result nullable,尤其是在使用 Swift 時,所以它知道結果是一個可選值:
(nullable SecIdentityRef)getSecIdentity
PPS你可能還想直接用 Swift 重寫你的代碼,因為它支持使用SecCertificate
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/513021.html
標籤:IOS迅速目标-c
上一篇:檔案加載不適用于通過FTP的NSURLSession
下一篇:如何從初級程式員變成高級程式員?
