Objective-C ARC-一种方法可以保留“自我"吗? [英] Objective-C ARC - does a method retain 'self'?
问题描述
这是安全的事吗?
__weak typeof (self) welf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[welf doStuff];
})
....
-(void)doStuff {
[_member1 someMethod];
....
[_member2 someMethodWithParam:_someCArray[1];];
}
据我了解ARC,对[welf doStuff]
的实际调用应该很好,因为welf
将有效(并且方法调用将继续进行),或者为nil
-调用任何方法nil
是在Objective-C中定义的安全行为,因此似乎没事.
As far as I understand ARC, the actual call to [welf doStuff]
should be fine, as welf
will either be valid (and the method call will proceed), or it will be nil
- calling any method on nil
is defined safe behaviour in Objective-C so that seems ok.
但是,一旦进入doStuff
,ARC会导致self
在方法调用期间被保留吗?如果确实如此,我认为应该没事...如果没有,那么self
可能会在方法调用的一半途中得到dealloc
的提示,然后我们将处于困境.
Once we get into doStuff
however, does ARC cause self
to be retained for the duration of the method call? If it does, I think we should be ok... If not, then self
could get dealloc
'ed halfway through the method call and then we'd be in a bad spot.
注意:我对此进行了谷歌搜索,但找不到任何明显的内容.也许只是很难搜索?
Note: I googled for this but couldn't find anything obvious. Perhaps it's just hard to search for?
谢谢!
推荐答案
事实证明,我最终在以下两个地方找到了答案: https://stackoverflow.com/a/18011581/234 以及此处: http://clang.llvm.org/docs/AutomaticReferenceCounting.html#self
As it turns out I found the answer eventually, both here: https://stackoverflow.com/a/18011581/234 and here: http://clang.llvm.org/docs/AutomaticReferenceCounting.html#self
self
始终在ARC下为unsafe unretained
,因此在我的示例中,它不是安全的,也没有什么可以阻止它通过我的doStuff
方法中途释放的.哎呀
self
is always unsafe unretained
under ARC, so in my example, it would NOT be safe, and there would be nothing to stop it getting deallocated partway through my doStuff
method. Ouch
这篇关于Objective-C ARC-一种方法可以保留“自我"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!