【问题标题】:Example of __strong usage in Objective CObjective C 中的 __strong 用法示例
【发布时间】: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");

【问题讨论】:

  • strongweak 适用于 ARC 代码,而不是 MRC 代码。
  • 开启 ARC!在启用 ARC 的情况下,您无法编写 retainrelease
  • @Cy-4AH - 我关闭了 ARC,因为我想用代码演示 __strong 和 __weak。我看到的所有强弱的例子都带有属性。
  • @rtsao,就像您注意到的那样:__strong__weak 在 MRC 中无效。

标签: ios objective-c strong-references


【解决方案1】:

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

【讨论】:

  • 好的,所以 __strong/__weak 或强/弱类型仅与 @property 一起使用?这意味着我不能这样做? __strong MyClass * ptr = .... 如果我们可以以这种方式使用它们,你能举个例子吗?
  • @rtsao 不,strongweak 不仅仅适用于房产。但它们仅适用于 ARC,而不适用于 MRC。
  • @rmaddy 知道了,你能举个例子吗?谢谢
  • @rtsao 在这里搜索__weak__strong,你会发现很多例子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多