首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Swift takeRetainedValue()和takeUnretainedValue()都是EXC_BAD_ACCESS

Swift takeRetainedValue()和takeUnretainedValue()都是EXC_BAD_ACCESS
EN

Stack Overflow用户
提问于 2022-09-22 11:28:16
回答 1查看 39关注 0票数 1

我有返回SecIdentityRef的objc函数

代码语言:javascript
运行
复制
+ (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;
}

我在桥接头中使用此函数导入类,然后在快速代码中使用它。

代码语言:javascript
运行
复制
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?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-23 06:25:21

当您从(我相信)任何核心基础集合中检索元素时,集合函数遵循得到-规则。这意味着在显式保留元素之前,您不会拥有它。因此,在代码的这一部分中:

(SecIdentityRef)CFDictionaryGetValue(identityDict,SecIdentityRef identityApp = kSecImportItemIdentity);CFRelease(项目);

本质上,您同时发布了itemsidentityApp,并返回了一个悬空指针(准确地说,是一个悬挂的核心基础引用)。只需在发布SecIdentityRef数组之前保留items实例,如下所示:

代码语言:javascript
运行
复制
CFRetain(identityApp);
CFRelease(items);
return identityApp;

P.S.,因为您的函数可能返回NULL,所以最好生成结果nullable,特别是在使用Swift时,因此它知道结果是一个可选值:

代码语言:javascript
运行
复制
+ (nullable SecIdentityRef)getSecIdentity

P.P.S.您可能还想直接用Swift重写代码,因为SecCertificate

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73813809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档