OGeek|极客世界-中国程序员成长平台

标题: ios - Objective C 中的 __strong 用法示例 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 16:14
标题: ios - Objective C 中的 __strong 用法示例

我在这里阅读了关于 __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: "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"**

Now let's say I use __strong keyword. If I add another strong reference like below, the Parent object should NOT call dealloc because we still have a strong reference (anotherFumu) to it. However, when I run it, the dealloc gets called. I do not see the strong reference having any effect.

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");



Best Answer-推荐答案


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

关于ios - Objective C 中的 __strong 用法示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32461808/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4