定義 一個(gè)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