Using objc_setAssociatedObject with weak references

后端 未结 5 2124
执笔经年
执笔经年 2020-12-23 21:34

I know that OBJC_ASSOCIATION_ASSIGN exists, but does it zero the reference if the target object is dealloced? Or is it like the old days where that reference needs to get n

5条回答
  •  無奈伤痛
    2020-12-23 22:36

    One more option similar to WeakObjectContainer:

    - (id)weakObject {
        id (^block)(void) = objc_getAssociatedObject(self, @selector(weakObject));
        return (block ? block() : nil);
    }
    
    - (void)setWeakObject:(id)object {
        id __weak weakObject = object;
        id (^block)(void) = ^{ return weakObject; };
        objc_setAssociatedObject(self, @selector(weakObject),
                                 block, OBJC_ASSOCIATION_COPY);
    }
    

提交回复
热议问题