Search code examples
ioskeychaincftypes

Getting error using CFTypeRef with ARC


I basically followed this tutorial, and soon realized the project wouldn't compile because I was using ARC. I managed to suppress all the errors using __bridge (>.>) but I am still getting one error message, and I managed to read this stack question, but didn't understand how to apply the resolution to my problem.

Basically the method that is giving me the problem looks like this:

+ (NSString*)getPasswordForKey:(NSString*)aKey
{
 NSString *password = nil;

 NSMutableDictionary *searchDictionary = [self dictionaryForKey:aKey];

 [searchDictionary setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
 [searchDictionary setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];


 NSData *result = nil;
 SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary, (CFTypeRef *)&result);

 if (result)
 {
    password = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];

 }
 return password;
} 

Solution

  • I think you are making unnecessarily complex type casts by trying to cast the pointer-to-pointer argument. How about this:

    CFTypeRef result = NULL;
    BOOL statusCode = SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary, &result);
    if (statusCode == errSecSuccess) {
        NSData *resultData = CFBridgingRelease(result);
        password = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
    }