Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using typeof(self) in Objective-C blocks to declare a strong reference

Using the weakSelf/strongSelf pattern to avoid creating a retain cycle in blocks, this code is pretty common:

typeof(self) __weak weakSelf = self;
void (^block)() = ^{
    typeof(weakSelf) strongSelf = weakSelf;
    // ...more code...
};

The question is, does changing the second typeof(weakSelf) to typeof(self) cause self to be captured in the block?

For example:

typeof(self) __weak weakSelf = self;
void (^block)() = ^{
    typeof(self) strongSelf = weakSelf; // does using typeof(self) here end up capturing self?
    // ...more code...
};

If self is not captured, is there any reason to prefer one way or the other?

like image 333
smileyborg Avatar asked Oct 07 '14 22:10

smileyborg


1 Answers

It shouldn't. If it does, it's a compiler bug.

The typeof expression doesn't actually reference the variable self or its value. It's strictly a reference to the expression's type, not its value. The expression is strictly a compile-time construct which doesn't survive into the compiled code.

I would prefer typeof(self), personally, but I don't think there's a strong argument to prefer one or the other.

like image 112
Ken Thomases Avatar answered Oct 19 '22 04:10

Ken Thomases