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

brainray picture brainray · May 19, 2014 · Viewed 20.4k times · Source

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.

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · May 19, 2014

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.