美文网首页
给分类中添加弱引用属性

给分类中添加弱引用属性

作者: 沧海小鱼儿 | 来源:发表于2020-04-02 13:00 被阅读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

相关文章

网友评论

      本文标题:给分类中添加弱引用属性

      本文链接:https://www.haomeiwen.com/subject/odcxphtx.html