我在这里阅读__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方法 . 但是没有调用dealloc,因为fumu引用的Parent对象仍然保留计数为1.正如预期的那样 .
使用__strong
就像声明的那样:
**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"**
现在让我们说我使用__strong关键字 . 如果我添加另一个强引用,如下所示,Parent对象不应该调用dealloc,因为我们仍然有一个强引用(anotherFumu) . 但是,当我运行它时,dealloc被调用 . 我没有看到强烈的参考有任何影响 .
Parent * __strong fumu = [[Parent alloc] init];
Parent * __strong anotherFumu = fumu;
[fumu release]; //Parent object dealloc gets called
请指教 . 谢谢
Result:
我打开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");
1 回答
alloc
是分配的缩写,所以当你打电话时Parent * fumu = [[Parent alloc] init];
你分配对象所以它的保留计数是= 1然后你调用
[fumu retain];
您的对象保留计数最多为2
然后当你打电话
[fumu release];
它增加了-1,所以你的最终计数将是1,这是正确的 .
强和弱是ARC类型,你不能在非ARC项目中使用它们 . 它与属性/变量一起使用......当你需要拥有对象时,你会想要使用
strong
,你在示例中创建对象时已经是"owning"对象了...https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW1