Question

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.

Was it helpful?

Solution

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

OTHER TIPS

Since the type of self in an Objective-C method is always a pointer type, __typeof(&*self) is redundant even in Objective-C++. __typeof(self) should always work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top