Search code examples
objective-ccocoaautomatic-ref-countingobjective-c-blocksweak-references

Generic typeof for weak self references


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 read about this it seems that the convention was to use __block typeof(self) bself = self;, which compiles but using __block to avoid retain cycles doesn't work anymore and __weak should be used instead.

However __weak typeof(self) bself = self; results in an error:

The type 'typeof (self)' (aka 'TUAccountsViewController *const __strong') already has retainment attributes set on it

Is there a way to use typeof or another call to generically create a weak reference to self?


Solution

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