Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of weak self assignment using __typeof

I found an odd line of code in the REActivityViewController project on GitHub and cannot understand it. It appears to avoid casting the value to the exact class that it is declared as, but I do not know why that would be necessary. I wonder if it is somehow important for inheritance.

Can anyone explain why this would be done?

__typeof(&*self) __weak weakSelf = self;

https://github.com/romaonthego/REActivityViewController/blob/master/REActivityViewController/REPocketActivity.m

I'd make this more clear by declaring it this way...

id __weak weakSelf = self;

And then within the block I can redeclare it as a strong reference.

REPocketActivity* __strong strongSelf = (REPocketActivity*)weakSelf;

Then I would use strongSelf within the block. When it goes out of scope it drops the strong reference safely.

like image 821
Brennan Avatar asked May 12 '13 17:05

Brennan


1 Answers

__typeof(self) is good for portability, since it's not binded to a specific class, nonetheless the &* trick looks definitely redundant. As far as my knowledge goes, in C, and consequently Objective-C, &*ptr is totally equivalent to ptr.

However, this may not hold true in other C-like languages such as C++, since operators can be overloaded and the semantic might not be as straightforward as it looks. In fact I've seen that &* already in C++ applications, especially when dealing with iterators. My guess here is that the author has a C++ background and that's why he inserted that redundant construct.

Anyway, I may be wrong and I'd love to hear a more sophisticated explanation, it there's any.

like image 133
Gabriele Petronella Avatar answered Oct 10 '22 01:10

Gabriele Petronella