Category中实现交换本类dealloc方法

项目中不恰当使用某个三方依赖导致了内存问题,想通过查看库中某对象的init和dealloc的具体结果,但是又不能使用@selector()获取dealloc方法,error是ARC禁止这么做。

但发现还有其他办法可以获取到原本的dealloc方法,以下是具体操作:

Method originalDealloc = class_getInstanceMethod(self, NSSelectorFromString(@"dealloc"));

Method swizzledDealloc = class_getInstanceMethod(self, @selector(ac_dealloc));

method_exchangeImplementations(originalDealloc, swizzledDealloc);
- (void)ac_dealloc {

[self ac_dealloc];

NSLog(@"buffer dealloc:%@",self);

}

但个人认为此操作可能会导致上架审核出现问题,因此最好只是用作调试。

更正:交换方法中添加的自定义操作一定要在[self ac_dealloc]之前。

- (void)ac_dealloc {

//do something

NSLog(@"buffer dealloc:%@",self);

[self ac_dealloc];

}

补充:如果想完全重写本类的dealloc方法的话,直接在分类中重写dealloc,这样的话在这个类的对象释放时只会走分类中重写的dealloc方法,而不会走本类中的dealloc。如果想在本类中的dealloc方法实现的内容的基础上添加内容,那就要使用上方“更正”中的代码所示的写法。

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.