Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does '__weak typeof(self)weakSelf = self;' mean

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.

like image 645
brainray Avatar asked May 19 '14 16:05

brainray


3 Answers

My guess is that it means: assign a weak reference to self with the name weakSelf and the typeof 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.

like image 158
Sergey Kalinichenko Avatar answered Nov 20 '22 20:11

Sergey Kalinichenko


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);
like image 29
CrimsonChris Avatar answered Nov 20 '22 21:11

CrimsonChris


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;
like image 5
Zev Eisenberg Avatar answered Nov 20 '22 20:11

Zev Eisenberg