Reputation: 927
Given that self is unsafe unretained in Objective-C, can we generally say that there is no good reason to ever call methods or access properties on weak objects? ie. never do this:
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf doStuff];
});
Sure, technically this may be ok if there is another strong reference to self that is guaranteed to remain in scope until after doStuff is called, but this is a very poor reason.
If there are no good reasons, then wouldn't it be a good idea for the compiler to simply reject such calls, at least behind a compiler option?
Upvotes: 1
Views: 566
Reputation: 535231
can we generally say that there is no strong reason to ever call methods or access properties on weak objects
No, that makes no sense. You are calling methods on weak objects all the time! For example, in Cocoa, most delegate
objects are weak
— as they would need to be, since it would be wrong for an object to retain its delegate. Yet calling methods on a delegate is the essence of the delegate pattern; otherwise, what is a delegate for?
Example: here's how the UIApplication delegate
is declared:
@property(nullable, nonatomic, assign) id<UIApplicationDelegate> delegate;
That is a non-ARC weak reference (that is what assign
means). Yet you would never say no messages can be sent to the app delegate, would you?
Upvotes: -1
Reputation: 25619
From the document you referenced:
For __weak objects, the current pointee is retained and then released at the end of the current full-expression. This must execute atomically with respect to assignments and to the final release of the pointee.
In other words, weakSelf
is automatically retained for the duration of the doStuff
method, so it's safe.
Generally, you would convert a weak reference into a strong reference if you're calling more than one method/property.
Upvotes: 2