Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block didn’t capture self in typeof,why?

For this:

self.block = ^{
    self.view.backgroundColor = [UIColor greenColor];
};

There is a retain cycle obviously.

However,there is no retain cycle if the self is in the typeof:

__weak typeof(self) weakSelf = self;
self.block = ^{
    __strong typeof(self) strongSelf = weakSelf;
    strongSelf.view.backgroundColor = [UIColor greenColor];
};

The self's dealloc is called even though the self is in the block.That means the block didn't capture self here.

Why?

like image 982
无夜之星辰 Avatar asked Mar 05 '23 09:03

无夜之星辰


1 Answers

typeof is not a function, it's a keyword and isn't used at runtime at all. All __strong typeof(self) is doing here is telling the compiler how to evaluate the symbol strongSelf. It doesn't cause any runtime code to be generated, because it doesn't matter at runtime what that type actually is. All those decisions are made at compile-time.

This is the same as defining something as int x; The runtime does not in any way have a reference to "int". It's just a C type.

typeof is technically a C extension, but Clang supports it as a keyword when in a gcc compatibility mode, which is the default. For more on the extension, see the GCC documentation.

like image 120
Rob Napier Avatar answered Mar 10 '23 00:03

Rob Napier