微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试创建一个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会立即崩溃

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐