加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 使用Unmanaged!作为NSMutableDictionary的关键

发布时间:2020-12-14 04:44:58 所属栏目:百科 来源:网络整理
导读:我正在尝试创建一个keychain查询,但我在使用Attribute Item Keys作为字典键时遇到了困难.在创建字典时,我可以将包含在数组中的属性项作为字典键传递,如此没有任何问题 genericPasswordQuery = NSMutableDictionary(objects: [kSecClassGenericPassword,ident
我正在尝试创建一个keychain查询,但我在使用Attribute Item Keys作为字典键时遇到了困难.在创建字典时,我可以将包含在数组中的属性项作为字典键传递,如此没有任何问题

genericPasswordQuery = NSMutableDictionary(objects: [kSecClassGenericPassword,identifier],forKeys: [kSecClass,kSecAttrGeneric])

但是,如果我尝试将另一个类似项添加到查询字典中,如下所示:

genericPasswordQuery.setObject(accessGroup,key:kSecAttrAccessGroup)

它抱怨密钥不符合NSCopying并提供类型错误:

“无法找到接受所提供参数的’setObject’的重载”

这是SecItemAdd的标准实现,但我在Swift中遇到问题.

解决方法

我想我找到了一个解决方案.从 docs:

When Swift imports APIs that have not been annotated,the compiler
cannot automatically memory manage the returned Core Foundation
objects. Swift wraps these returned Core Foundation objects in an
Unmanaged structure. All indirectly returned Core Foundation
objects are unmanaged as well.

When you receive an unmanaged object from an unannotated API,you
should immediately convert it to a memory managed object before you
work with it. That way,Swift can handle memory management for you.
The Unmanaged structure provides two methods to convert an
unmanaged object to a memory managed object—takeUnretainedValue() and
takeRetainedValue().

目前的实施:

genericPasswordQuery = NSMutableDictionary(objects: [kSecClassGenericPassword,kSecAttrGeneric])

var kSecAttrAccessGroupSwift: NSString = kSecAttrAccessGroup.takeRetainedValue() as NSString
genericPasswordQuery.setObject(accessGroup,forKey: kSecAttrAccessGroupSwift)

这在Xcode中运行良好,但是当我添加.takeRetainedValue时,Playground会立即崩溃

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读