网上有很多版本,我提供一种不用加新类就可以实现的方法。
创建NSObject的Category
NSObject+Ext.h
#import <Foundation/Foundation.h>
typedef void (^DeallocBlock)();
@interface NSObject (Ext)
@property (nonatomic, weak) id weakObj;
@property (nonatomic, copy) DeallocBlock block;
@end
NSObject+Ext.m
#import "NSObject+Ext.h"
#import <objc/runtime.h>
static NSString *WEAK_KEY = @"weakObj";
static NSString *BLOCK_KEY = @"block";
@implementation NSObject (Ext)
- (id)weakObj {
return objc_getAssociatedObject(self, &WEAK_KEY);
}
- (void)setWeakObj:(id)weakObj {
[weakObj setBlock:^() {
objc_setAssociatedObject(self, &WEAK_KEY, nil, OBJC_ASSOCIATION_ASSIGN);
}];
objc_setAssociatedObject(self, &WEAK_KEY, weakObj, OBJC_ASSOCIATION_ASSIGN);
}
- (DeallocBlock)block {
return objc_getAssociatedObject(self, &BLOCK_KEY);
}
- (void)setBlock:(DeallocBlock)block {
objc_setAssociatedObject(self, &BLOCK_KEY, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
- (void)dealloc {
self.block ? self.block() : nil;
objc_setAssociatedObject(self, &BLOCK_KEY, nil, OBJC_ASSOCIATION_ASSIGN);
}
#pragma clang diagnostic pop
@end
测试用法
NSObject *obj1 = [NSObject new];
NSObject *obj2 = [NSObject new];
obj1.weakObj = obj2;
NSLog(@"%@", obj1.weakObj);
obj2 = nil;
NSLog(@"%@", obj1.weakObj);