ARC and __unsafe_unretained

Posted by J Shapiro on Stack Overflow See other posts from Stack Overflow or by J Shapiro
Published on 2012-11-20T16:11:55Z Indexed on 2012/11/20 17:00 UTC
Read the original article Hit count: 175

I think I have a pretty good understanding of ARC and the proper use cases for selecting an appropriate lifetime qualifiers (__strong, __weak, __unsafe_unretained, and __autoreleasing). However, in my testing, I've found one example that doesn't make sense to me.

As I understand it, both __weak and __unsafe_unretained do not add a retain count. Therefore, if there are no other __strong pointers to the object, it is instantly deallocated. The only difference in this process is that __weak pointers are set to nil, and __unsafe_unretained pointers are left alone.

If I create a __weak pointer to a simple, custom object (composed of one NSString property), I see the expected (null) value when trying to access a property:

Test * __weak myTest = [[Test alloc] init];
myTest.myVal = @"Hi!";
NSLog(@"Value: %@", myTest.myVal); // Prints Value: (null)

Similarly, I would expect the __unsafe_unretained lifetime qualifier to cause a crash, due to the resulting dangling pointer. However, it doesn't. In this next test, I see the actual value:

Test * __unsafe_unretained myTest = [[Test alloc] init];
myTest.myVal = @"Hi!";
NSLog(@"Value: %@", myTest.myVal); // Prints Value: Hi!

Why doesn't the __unsafe_unretained object become deallocated?

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about automatic-ref-counting