Can an Objective-C be freed if an instance method is called on it?

Consider the following: an instance of the Objective-C class refers to one strong link and one weak link (under ARC). In thread X, the method is called instantly through a weak reference. In thread Y, the strong reference is broken so that there are no stronger references to the instance, and it must be freed.

Is it possible that an object can be freed from thread Y during the execution of a method in thread X? Likewise, calls a method call on an object to "save" this object until the method returns?

+7
multithreading objective-c
source share
1 answer

ARC actually preserves weak references before calling instance methods on them and frees them after the call.

I studied this problem and was fixed by a colleague after he showed him this stack question. He pointed it out: http://lists.apple.com/archives/objc-language/2012/Aug/msg00027.html

Of course, in the assembly, ARC saves and releases around the call via a weak link.

One time you want to listen to CLANG_WARN_OBJC_RECEIVER_WEAK to check for nil when nil can 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 a safer way:

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

All Articles