Understand __Bridge

来源:互联网 发布:wind数据库账号 编辑:程序博客网 时间:2024/06/05 13:30

  I didn't understand the __bridge properly for a long time so that i took some hours to read documentation.

  from documentation,I know what's the duty of the core key__bridge.

  Ok.

  Duty: Convert Objective-c type into CoreFoundation type and reconvert.

  There are three methods to do this:


  Get from Documentation:

  • __bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership.(weak references)

  • __bridge_retained or CFBridgingRetain casts an Objective-C pointer to a Core Foundation pointer and also transfers ownership to you.

    You are responsible for calling CFRelease or a related function to relinquish ownership of the object.(strong references, you have to call CFRelease to relinquish memory Because the ownership transfer to yourself)

  • __bridge_transfer or CFBridgingRelease moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC.

    ARC is responsible for relinquishing ownership of the object.(Reconvert to objective-c and take the ownership to ARC)


    Example from documentation:

    NSLocale *gbNSLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
    CFLocaleRef gbCFLocale = (__bridge CFLocaleRef)gbNSLocale;
    CFStringRef cfIdentifier = CFLocaleGetIdentifier(gbCFLocale);
    NSLog(@"cfIdentifier: %@", (__bridge NSString *)cfIdentifier);
    // Logs: "cfIdentifier: en_GB"
     
    CFLocaleRef myCFLocale = CFLocaleCopyCurrent();
    NSLocale *myNSLocale = (NSLocale *)CFBridgingRelease(myCFLocale);
    NSString *nsIdentifier = [myNSLocale localeIdentifier];
    CFShow((CFStringRef)[@"nsIdentifier: " stringByAppendingString:nsIdentifier]);
    // Logs identifier for current locale

0 0