首页 文章

Objective C中__strong用法的示例

提问于
浏览
2

我在这里阅读__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 回答

相关问题