可以在调用实例方法的同时释放Objective-C对象吗? [英] Can an Objective-C object be deallocated while an instance method is being invoked on it?

查看:83
本文介绍了可以在调用实例方法的同时释放Objective-C对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:一个强引用和一个弱引用(在ARC中)引用了Objective-C类的实例.在线程X上,通过弱引用在实例上调用方法.在线程Y上,强引用被破坏,因此不再有对该实例的强引用,应该将其释放.

Consider the following: An instance of an Objective-C class is referenced by one strong reference and one weak reference (under ARC). On thread X, a method is called on the instance via the weak reference. On thread Y, the strong reference is broken such that there are no more strong references to the instance, and it should be deallocated.

这种情况是否可能,因为方法可能在线程X上执行时,对象可能会在线程Y上被释放?同样,在对象上调用方法是否会保留"该对象,直到该方法返回?

Is this situation possible, in that the object might be deallocated on thread Y while the method is executing on thread X? Similarly, does invoking a method on an object 'retain' that object until the method returns?

推荐答案

ARC实际上在调用弱引用之前确实保留了弱引用,并在调用后释放了弱引用.

ARC actually does retain weak references before calling instance methods on them, and releases after the call.

我正在研究此问题,在向他展示了这个stackoverflow问题后,一位同事对其进行了纠正.他指出了这一点: http://lists.apple.com/archives/objc-language/2012/Aug/msg00027.html

I was researching this issue and was corrected by a colleague after showing him this stackoverflow question. He pointed to this: http://lists.apple.com/archives/objc-language/2012/Aug/msg00027.html

果然,在程序集中,ARC会在弱引用上的调用周围保留并释放.

Sure enough, in the assembly, ARC retains and releases around an invocation on a weak reference.

您一次想收听CLANG_WARN_OBJC_RECEIVER_WEAK是为了进行nil检查,否则nil可能会导致错误.

One time you will want to listen to CLANG_WARN_OBJC_RECEIVER_WEAK is for nil checks, when nil could cause an error.

if (self.weakRefToParent) {
    //self.weakRefToParent could be dealloced and set to nil at this line
    NSString *name = [self.weakRefToParent name]; //CLANG_WARN_OBJC_RECEIVER_WEAK warning
    [self.namesArray addObject:name];  //name is nil, NSInvalidArgumentException
}

这是更安全的方法:

Parent *strongRefToParent = self.weakRefToParent;
if (strongRefToParent) {
    NSString *name = [strongRefToParent name];
    [self.namesArray addObject:name];
}

这篇关于可以在调用实例方法的同时释放Objective-C对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆