By books first explains the problem (using ARC) about “unvalid” references, like in this example:
NSDate* date1=[[NSDate alloc]init];
NSDate* date2=date1;
[date1 release];
NSLog(@"%@",date2); // bad access
So I have understood the retain/release mechanism: in this case the instruction would be:
date2=[date1 retain];
But when it talks about strong/weak references, it sounds like a contradiction to me:
“By default, references are strong. If you assign an object to a strong reference, ARC assumes that you want that object to stick around and retains it implicitly”
Isn’t this a contradiction of what has said before?
date2 is strong by default, so it should implicitly retain date1 and there wouldn’t be a bad access exception.
Of course I have misunderstood something, could someone explain this better to me?
Strong is the default because it’s typically what you want, but using ARC, the compiler analyzes how long the object’s life needs to be and releases the memory at the appropriate time. For example:
Weak references only keep the object around while it has one or more other strong references to it. As soon as the last strong reference is broken, the object is released by the compiler and the weak object reference (the variable) is changed to
nilby the runtime. This makes weak variables almost useless in the local scope like the example above. For example:To see an example of a weak and strong variable working together in the local scope (this would have only severely limited usefulness and is really shown here only to demonstrate weak variable references):