2

我在这里阅读了关于 __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");
4

1 回答 1

2

alloc是 allocate 的缩写,因此当您调用
Parent * fumu = [[Parent alloc] init];
时分配对象,因此其保留计数为 =1,然后您调用[fumu retain];
对象的保留计数最多为 +2,
然后当您调用[fumu release];
它时添加 -1,因此您的最终计数将为 +1,即正确的。

Strong 和 Weak 是 ARC 类型,你不能在非 ARC 项目中使用它们。strong它与属性/变量一起使用...当您需要拥有该对象时,您会想要使用该对象,当您在示例中创建对象时,您已经“拥有”该对象...

https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW1

于 2015-09-08T15:55:43.620 回答