denysowova
denysowova

Reputation: 111

What does __typeof(&*self) in Objective-C mean? How does it differ from __typeof(self)?

I was looking through some MVVM sample code and run into this line:

__weak __typeof(&*self) weakSelf = self;
/*later used in some block*/

I understand what __weak and typeof(self) are for. Why not just use __weak __typeof(self) or __weak ViewController *weakSelf? What are the reference and asterisk (&*self) being used for?

Upvotes: 5

Views: 357

Answers (2)

bbum
bbum

Reputation: 162712

*& is a C++-ism. It is used to pass by reference pointer parameters.

&* looks like someone was very confused and ended up writing code that is effectively a no-op. However, if that is Objective-C++ code, then &* might very well do something (iirc, smart pointers can end up requiring weird indirection usage to do certain things).

Most of the projects I work on use __weak typeof(self) weakSelf = self;.

Upvotes: 2

Nikhil
Nikhil

Reputation: 73

__weak __typeof(&*self)weakSelf = self;

__weak HomeVC *weakSelf2 = self;

NSLog(@"%@", weakSelf);  // This gives you the reference of the View Controller Object
NSLog(@"%p", weakSelf);  // This gives you only the address of the View Controller Object
NSLog(@"%@", weakSelf2); // Same as 1
NSLog(@"%p", weakSelf2); // Same as 2
NSLog(@"%@", &*self);    // Same as 1
NSLog(@"%p", &*self);    // Same as 2

// In the above logs you can notice the difference just by changing the format specifier. Hope this helps.

Upvotes: 1

Related Questions