Generic typeof for weak self references

前端 未结 10 868
误落风尘
误落风尘 2020-12-07 11:29

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

相关标签:
10条回答
  • 2020-12-07 12:29

    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.

    0 讨论(0)
  • 2020-12-07 12:29

    Generic Weakself Reference (No Import Required + Snippet)


    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.


    Xcode 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

    0 讨论(0)
  • 2020-12-07 12:30

    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.

    0 讨论(0)
  • 2020-12-07 12:31

    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
    
    0 讨论(0)
提交回复
热议问题