给分类中添加弱引用属性

2020-04-02  本文已影响0人  沧海小鱼儿

定义 一个block

typedef id weakid;
typedef weakid(^WeakReference)(void);

WeakReference packWeakReference(id ref) {
    __weak weakid weakRef = ref;
    return ^{
        return weakRef;
    };
}

weakid unpackWeakReference(WeakReference closure) {
    return closure ? closure() : nil;
}
@implementation ViewController (WeakDelegate)

- (void)setDelegate:(id)delegate
{
    objc_setAssociatedObject(self, @selector(delegate), packWeakReference(delegate), OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (id)delegate
{
    return unpackWeakReference(objc_getAssociatedObject(self, @selector(delegate)));
}

@end
上一篇 下一篇

猜你喜欢

热点阅读