给分类中添加弱引用属性

定义 一个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

你可能感兴趣的:(给分类中添加弱引用属性)