iPhone fetch data dictionary from keychain

前端 未结 3 1917
无人共我
无人共我 2020-12-13 02:59

So I\'m trying to convert an old project to Automatic Reference Counting. I\'m trying to use the conversion tool that xCode has but it says to fix a couple things before it

3条回答
  •  半阙折子戏
    2020-12-13 03:52

    You don't need to disable ARC for this; you just need to declare the query's result as a CFDictionaryRef, then cast it to an NSDictionary after the call.

    /*1*/ CFDictionaryRef cfquery = (__bridge_retained CFDictionaryRef)genericPasswordQuery;
    /*2*/ CFDictionaryRef cfresult = NULL;
    /*3*/ OSStatus status = SecItemCopyMatching(cfquery, (CFTypeRef *)&cfresult);
    /*4*/ CFRelease(cfquery);
    /*5*/ NSDictionary *result = (__bridge_transfer NSDictionary *)cfresult;
    

    Couple of remarks:

    • In line 1, we convert the query from Cocoa land to Core Foundation country. We use __bridge_retained to make sure ARC does not release and deallocate the object while we are working with it. This kind of bridging cast retains the object, so to prevent leaks, it must be followed with a corresponding CFRelease somewhere. SecItemCopyMatching definitely will not release the query for us, so if we use a retained bridge, then we need to release the resulting Core Foundation object ourself. (Which we do in line 4.)
    • Lines 2, 3, and 4 are pure C code using Core Foundation types, so ARC will have nothing to do or complain about them.
    • In line 5, we tell ARC that SecItemCopyMatching has created its result with a retain count of 1, which we are responsible for releasing. (We know this because it has "Copy" in its name.) __bridge_transfer lets ARC know about this responsibility, so it will be able to do it for us automatically.
    • Don't cast the immutable Core Foundation dictionary returned by SecItemCopyMatching to NSMutableDictionary; that's just wrong. Also, it is against general Cocoa style conventions that buildSearchQuery returns an NSMutableDictionary. Simple NSDictionarys would work fine in both cases.

    The rule of thumb here is that __bridge_retained needs to be followed by a CFRelease, while the result from a "Copy" or "Create" function must be cast into Cocoa-land using __bridge_transfer.

提交回复
热议问题