Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Unmanaged<AnyObject>! as key in NSMutableDictionary

Tags:

swift

keychain

I'm trying to create a keychain query but I'm having difficulties with using Attribute Item Keys as dictionary keys. When creating the dictionary I can pass the attribute items wrapped in an array as dictionary keys like so without any issues

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

However if I try to add another similar item to the query dict like so:

genericPasswordQuery.setObject(accessGroup, key:kSecAttrAccessGroup)

It complains that the key doesn't conform to NSCopying and supplies the type error:

"could not find an overload for 'setObject' that accepts the supplied arguments"

This is the standard implementation of a SecItemAdd but I'm having issues doing it in Swift.

like image 559
Pasan Premaratne Avatar asked Feb 13 '23 17:02

Pasan Premaratne


1 Answers

I think I figured out a solution. From the 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().

Current implementation:

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

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

This runs fine in Xcode but a Playground immediately crashes when I add .takeRetainedValue

like image 63
Pasan Premaratne Avatar answered Feb 26 '23 21:02

Pasan Premaratne