我们在开发过程经常会遇到这样的情况,我们想监测一个NSObject对象到底有没有释放掉,通常的做法就是继承于一个父类在其dealloc方法中进行NSLog打印输出了,这时候我们有没有思考可以很方便的去实现dealloc方法的捕获?下面和大家分享一个简单的方法,来实现这个过程。
NSObject *object = [NSObject new];
[object jf_DeallocExcute:^{
NSLog(@"对象释放了");
}];
复制代码
通过上面的演示,主要思路是:我们可以通过添加一个的分类就能实现dealloc 方法的捕获
首先看一下具体的实现
JFDeallocExecute 类
typedef void(^JFDeallocExecuteBlock)(void);
@interface JFDeallocExecute : NSObject
- (instancetype)initWithBlock:(JFDeallocExecuteBlock)block;
@end
@interface JFDeallocExecute ()
@property (nonatomic, copy) JFDeallocExecuteBlock deallocExecuteBlock;
@end
@implementation JFDeallocExecute
- (instancetype)initWithBlock:(JFDeallocExecuteBlock)block{
self = [super init];
if (self) {
_deallocExecuteBlock = [block copy];
}
return self;
}
- (void)dealloc{
_deallocExecuteBlock ? _deallocExecuteBlock() : nil;
}
复制代码
NSObject+JFDeallocExecute 分类
@interface NSObject (JFDeallocExecute)
- (void)jf_DeallocExcute:(JFDeallocExecuteBlock)block;
@end
const void *JFDeallocExecutekey = nil;
@implementation NSObject (JFDeallocExecute)
- (NSMutableArray *)deallocExecutors{
NSMutableArray *array = objc_getAssociatedObject(self, JFDeallocExecutekey);
if (!array) {
array = [NSMutableArray arrayWithCapacity:1];
objc_setAssociatedObject(self, JFDeallocExecutekey, array, OBJC_ASSOCIATION_RETAIN);
}
return array;
}
- (void)jf_DeallocExcute:(JFDeallocExecuteBlock)block{
if (block) {
JFDeallocExecute *executor = [[JFDeallocExecute alloc] initWithBlock:block];
[[self deallocExecutors] addObject:executor];
}
}
复制代码
通过上述代码,实现思路已经很明了了,通过给NSObject 类动态的添加一个数组属性,数组中保存一个中间对象(这个中间对象保存外部的block),当NSObject对象销毁的时候,NSObject属性对象NSMutableArray 销毁,其内部的元素也就销毁了,当调用中间对象的dealloc方法时候,执行外部的block.
提供一个Example ,github 地址: