gpt4 book ai didi

ios - __strong 在 Objective C 中的用法示例

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:57:55 27 4
gpt4 key购买 nike

我在这里阅读了有关 __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];

调用了父对象的初始化方法。但是 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"**

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

最佳答案

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 - __strong 在 Objective C 中的用法示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32461808/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com