Can an Objective-C object be deallocated while an instance method is being invoked on it?

前端 未结 1 987
不思量自难忘°
不思量自难忘° 2021-01-11 20:30

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

相关标签:
1条回答
  • 2021-01-11 21:15

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

    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

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

    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
    }
    

    This is the safer way:

    Parent *strongRefToParent = self.weakRefToParent;
    if (strongRefToParent) {
        NSString *name = [strongRefToParent name];
        [self.namesArray addObject:name];
    }
    
    0 讨论(0)
提交回复
热议问题