I use below code to test arc and help to understand the ARC
NSArray __strong* myArray = [NSArray arrayWithObjects:@"123", nil];
NSArray __weak* yourArray = myArray;
NSArray __unsafe_unretained* theirArray = yourArray;
myArray = nil;
NSLog(@"yourArray = %@, theirArray = %@", yourArray, theirArray);
As my understand, the log should be:yourArray = (null), theirArray = (null)
In face the log is:
yourArray = (
123
), theirArray = (
123
)
if I change the code and remove the __unsafe_unretained:
NSArray __strong* myArray = [NSArray arrayWithObjects:@"123", nil];
NSArray __weak* yourArray = myArray;
//NSArray __unsafe_unretained* theirArray = yourArray;
myArray = nil;
NSLog(@"yourArray = %@", yourArray);
the log is right:yourArray = (null)
why if I add __unsafe_unretained local variables to weak reference my NSArray object, it like retain or strong my NSArray object.
Any one can help to answer the doubt.
Best Regards
The compiler is pretty good about figuring out what object’s lifetimes are during this kind of simple example with limited scope. It can tell that it shouldn’t release the array until the end of the scope is reached (or at least the end of the last read is reached with these simple assignments).
If you use an ivar that’s marked
__unsafe_unretained, assign it after the weak assignment, and build with full optimizations, you might see different results, even in this kind of simple case. Also, basically while the compiler may be able to deal with situations like this, where the__weakvariable is still set and the__unsafe_unretainedvariable is still able to be read without disaster, the point is that you can’t count on it to behave that way. What you can count on is that a__weakvariable will be nil’d out after its last__strongreference goes away, and that the compiler won’t insert retain/release directives for an__unsafe_unretainedvariable. As long as you follow the rules, you will have predictable results. As soon as you don’t follow the rules, anything that happens or doesn’t happen is undefined… so it may work in the simulator and iPod 4G’s but fail horribly on 4S and 5 while working half the time on any iPad… the point is, the result is undefined.