Generic typeof for weak self references
In the latest clang version Apple clang version 4.0 (tags/Apple/clang-421.1.48) (based on LLVM 3.1svn), i.e. Xcode 4.4+, the __typeof__((__typeof__(self))self)
trick is not necessary anymore. The __weak typeof(self) bself = self;
line will compile just fine.
This works!
__typeof__(o) __weak
Which I've defined in my BBlock project as BBlockWeakSelf
which can be used like this:
BBlockWeakSelf wself = self;
https://github.com/kgn/BBlock/blob/master/BBlock.h
Edited based on Aleph7's response.
The correct way to do this is
__weak ActualClassName* weakSelf = self;
Macros only make it unclear what the variable actually is, and what you're actually doing with it, in addition to adding non-portable meta-language to your code.
If you need a more generic version of the class than ActualClassName provides, you aren't dealing with self
anymore, since where self
is defined, so is the class of self
defined.
In those cases, you should use the closest base class name in your inheritance tree, NSObject
or better, never id
, e.g.
__weak MyBaseClassName* weakObject = object;