I am trying to figure out a way to use typeof
to create a weak reference to self
for use in blocks to avoid retain cycles.
When I first rea
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.
In my experience, the way to go is to use:
__typeof__(self) __weak weakSelf = self;
Note how the ownership qualifier belongs in front of the actual variable.
It's very apparent what's happening when it is used and it can be made into a handy code snippet in Xcode which makes it even easier to use in any project or class where this is needed. (I use "ws" as the snippet's completion shortcut)
Hmm.. I need a weak reference here..
ws{return}
Done. No need to ever include a header in future projects for this, just use the snippet.
Title: Generic Weak Self Reference
Platform: All
Language: Objective-C
Completion Shortcut: ws
Completion Scopes: Function or Method
Code: __typeof__(self) __weak weakSelf = self;
Edit: Added note about ownership qualifier position based on comments, and Xcode Snippet Info
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.
I have this macro
#define weaken(object) __typeof__(self) __weak weakSelf = object
And i use it like this
weaken(self);
//The block referencing weakSelf goes here