我在这里阅读了关于 __strong 参考和 __weak 参考用法的信息:iOS5 中强存储和弱存储的解释
我尝试编写一些代码来展示这些知识。但是,__strong 在对象被释放时并未将其保留在内存中。第一次我这样做:
Parent * fumu = [[Parent alloc] init];
[fumu release];
一切都按预期工作。调用父对象init,释放时调用dealloc。
第二我这样做了:
Parent * fumu = [[Parent alloc] init];
[fumu retain];
[fumu release];
调用了 Parent 对象的 init 方法。但是因为 fumu 引用的 Parent 对象的保留计数仍然为 1,所以没有调用 dealloc。正如预期的那样。
使用 __strong就像声明的那样:
**强:“将其保留在堆中,直到我不再指向它为止” 弱:“只要其他人强烈指向它,就保持这个”**
现在假设我使用 __strong 关键字。如果我像下面添加另一个强引用,则父对象不应该调用 dealloc,因为我们仍然有一个强引用(anotherFumu)。但是,当我运行它时,会调用 dealloc。我没有看到强参考有任何影响。
Parent * __strong fumu = [[Parent alloc] init];
Parent * __strong anotherFumu = fumu;
[fumu release]; //Parent object dealloc gets called
请指教。谢谢
结果:
我打开了 ARC,并简单地使用 nil 将强指针指向远离 Parent 对象,从而能够正确地看到 __strong 和 __weak 的行为,如下所示:
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");