This is used in the weakify pattern of Objective-C
My guess is that it means: assign a weak reference to self with the name 'weakSelf' and the typeof self (e.g. MyViewController)
If it's correct and looks obvious to you: I want to be absolutely sure to get this right. Thanks.
My guess is that it means: assign a weak reference to self with the name
weakSelf
and thetypeof
self (e.g.MyViewController
)
Yes, that is almost exactly what it means. The type of self
would be MyViewController*
(with an asterisk) not MyViewController
.
The idea behind using this syntax instead of simply writing
MyViewController __weak *weakSelf = self;
is making it easier to refactor the code. The use of typeof
also makes it possible to define a code snippet that can be pasted anywhere in your code.
Using @weakify
and @strongify
from libExtObjC helps to simplify the "weak-strong dance" one has to do sometimes around blocks.
Example!
__weak __typeof(self) weakSelf = self;
__weak __typeof(delegate) weakDelegate = delegate;
__weak __typeof(field) weakField = field;
__weak __typeof(viewController) weakViewController = viewController;
[viewController respondToSelector:@selector(buttonPressed:) usingBlock:^(id receiver){
__strong __typeof(weakSelf) strongSelf = weakSelf;
__strong __typeof(weakDelegate) strongDelegate = weakDelegate;
__strong __typeof(weakField) strongField = weakField;
__strong __typeof(weakViewController) strongViewController = weakViewController;
versus...
@weakify(self, delegate, field, viewController);
[viewController respondToSelector:@selector(buttonPressed:) usingBlock:^(id receiver){
@strongify(self, delegate, field, viewController);
Your interpretation is correct. However, I find that when it is written that way, it is slightly confusing to read. I prefer it with an additional space after typeof(self)
:
__weak typeof(self) weakSelf = self;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With