objective-ctypeofweak

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.


Solution

  • 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.