KudoCC
KudoCC

Reputation: 6952

When using __bridge, will the object-c object changed to `__unsafe_unretained` implicitly

Here is the code:

{
    CFMutableStringRef str = CFStringCreateMutableCopy(NULL, 1000, CFSTR("Hello World") );
    NSString *value = (__bridge NSString *)str ;
    NSLog(@"%@", value) ;
    CFRelease(str) ;
}

The default attribute of value is strong, will its attribute change to __unsafe_unretained after assign it to a (__bridge NSString *)str. In my opinion, if not, value will be sent release method when value is out of its scope.

Can you show me how compiler handles this when using __bridge cast from CF to Object-C Object.

Upvotes: 0

Views: 659

Answers (1)

rob mayoff
rob mayoff

Reputation: 385700

Here's your assignment:

NSString *value = (__bridge NSString *)str ;

That has the same effect as writing this would if ARC were disabled:

NSString *value = nil;
objc_storeStrong(&value, (id)str);

The __bridge cast doesn't change the string's reference count, but the assignment to a __strong variable turns into a call to objc_storeStrong, and objc_storeStrong retains str. This retain needs to be balanced by a release.

After the last use of value, the compiler inserts this:

objc_release(value);

This has the same effect as writing [value release] would if ARC were disabled.

Now suppose you wrote this:

NSString *__unsafe_unretained value = (__bridge NSString *)str;

That has the same effect as writing this would if ARC were disabled:

NSString *value = (id)str;

This time, there's no release to be balanced, and the compiler doesn't insert anything extra after the last use of value. But if you use value after you CFRelease(str), you will probably crash. That's why it's “unsafe”.

Upvotes: 3

Related Questions