I was reading about __strong reference and __weak reference usage here: Explanation of strong and weak storage in iOS5
I tried writing a bit of code to demonstrate this knowledge. However, the __strong did not keep the object in memory as it was released. 1st I did this:
Parent * fumu = [[Parent alloc] init]; [fumu release]; Everything works as expected. Parent object init gets called, When released, the dealloc gets called.
2nd I did this:
Parent * fumu = [[Parent alloc] init]; [fumu retain]; [fumu release]; The Parent object init method was called. But dealloc was not called because the Parent object that fumu references still has retain count of 1. As expected.
Using __strongAs stated:
**Strong: "keep this in the heap until I don't point to it anymore" Weak: "keep this as long as someone else points to it strongly"**
Now let's say I use __strong keyword. If I add another strong reference like below, the Parent object should NOT call dealloc because we still have a strong reference (anotherFumu) to it. However, when I run it, the dealloc gets called. I do not see the strong reference having any effect.
Parent * __strong fumu = [[Parent alloc] init]; Parent * __strong anotherFumu = fumu; [fumu release]; //Parent object dealloc gets called Please advise. thanks
Result:
I turned on ARC, and simply used nil to point the strong pointers away from the Parent object, and thus be able to correctly see the behavior of __strong and __weak like so:
Parent * fumu = [[Parent alloc] init]; __strong Parent * strongFumu = fumu; __weak Parent * weakFumu = fumu; fumu = nil; //your auto variables window should show that both trongFumu and weakFumu are still valid with an address NSLog(@"weakFumu should be valid here, because strongFumu is still pointing to the object"); strongFumu = nil; //when strongFumu points away to nil, weakPtr will then also change to nil NSLog(@"weakFumu should be nil here");
strongandweakare useful with ARC code, not MRC code.retainandreleasewith ARC enabled.__strongand__weakhave no effect in MRC.