Generic typeof for weak self references

前端 未结 10 879
误落风尘
误落风尘 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

    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

提交回复
热议问题