【发布时间】:2015-09-08 15:34:25
【问题描述】:
我在这里阅读了关于 __strong 引用和 __weak 引用的用法:Explanation of strong and weak storage in iOS5
我尝试编写一些代码来展示这些知识。但是,__strong 在对象被释放时并未将其保留在内存中。 我第一次这样做:
Parent * fumu = [[Parent alloc] init];
[fumu release];
一切都按预期进行。调用父对象init,释放时调用dealloc。
第二次我这样做了:
Parent * fumu = [[Parent alloc] init];
[fumu retain];
[fumu release];
调用了父对象的 init 方法。但是由于 fumu 引用的 Parent 对象的保留计数仍然为 1,所以没有调用 dealloc。正如预期的那样。
使用 __strong如前所述:
**强:“将其保留在堆中,直到我不再指向它为止” 弱:“只要其他人强烈指出,就保持这个”**现在假设我使用 __strong 关键字。如果我像下面这样添加另一个强引用,则 Parent 对象不应该调用 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");
【问题讨论】:
-
strong和weak适用于 ARC 代码,而不是 MRC 代码。 -
开启 ARC!在启用 ARC 的情况下,您无法编写
retain和release。 -
@Cy-4AH - 我关闭了 ARC,因为我想用代码演示 __strong 和 __weak。我看到的所有强弱的例子都带有属性。
-
@rtsao,就像您注意到的那样:
__strong和__weak在 MRC 中无效。
标签: ios objective-c strong-references