iOS bridge vs bridge_transfer

后端 未结 4 1530
旧巷少年郎
旧巷少年郎 2021-01-31 03:27

I\'m confused with bridge and bridge_transfer, is this correct?

-(void)getData{
    ABAddressBookRef addressBook = ABAddressBookCreate(         


        
4条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 03:54

    It is very very simple, When you use ARC (automatic reference counting) the compiler will take care of counting how many objects are being pointed by your variables. When the count goes to 0 the object is automatically dealocated. SO for things that come from a low level structure, like core foundation, the compiler doesnt know what to do. So you use BRIDGE if you just want to tell the compiler "ignore this one, i will release it when i need it". or Bridge transfer if you want to say "Treat this as an object and release it when the reference goes to 0).

    When you do this, you create a copy that under normal circumstances should be released by a "CFRelease":

    ABAddressBookCopyArrayOfAllPeople(addressBook)
    

    However by adding this, you are transferring the ownership to an objective-c object:

    NSArray *allPeople = (__bridge_transfer NSArray*)........
    

    So the NSArray will be managed by ARC.


    Note that as JRG mentions, doing this:

    CFRelease(addressBook);
    

    Does not affect the newly created object in anyway, but instead the original one which you still have to manually release: (It's easy to tell because those methods usually have the create or copy keywords in their names)


    Something that does not happen in your code but you should be careful with is that releasing core foundation objects which are NULL with CFRelease will cause an error. As Paul mentions in his comment.

提交回复
热议问题