一個(gè)朋友群里討論能夠hook住dealloc方法嗎蝙叛?然后當(dāng)時(shí)我就想為什么hook不住嗎?所以我就在群里問為什么呢粘都?奈何他也不知道廓推。所以剩下的只能是我自己去嘗試一下了。
大家hook方法的時(shí)候第一步肯定是首先獲取到方法的實(shí)現(xiàn)翩隧。用到如下代碼:
Method repMethod = class_getInstanceMethod([self class], @selector(replaceDelloc));
奈何我用上述方法寫的時(shí)候Xcode編譯器會(huì)報(bào)編譯錯(cuò)誤
ARC forbids use of 'dealloc' in a @selector
哦樊展!作者終于明白朋友口中的hook不住,其實(shí)就是因?yàn)閷懛ǖ膯栴}堆生,Xcode不讓我們這么寫专缠,所以談何去hook呢?既然不能這么寫那我們換種寫法不就行了嗎?是的淑仆。哈哈
Method oriMethod = class_getInstanceMethod([self class], NSSelectorFromString(@"dealloc"));
我們通過字符串獲取到方法就可以了涝婉,這樣Xcode在編譯的時(shí)候檢查不到啦。
+(void)load{
// Method oriMethod = class_getInstanceMethod([self class], @selector(dealloc));
Method oriMethod = class_getInstanceMethod([self class], NSSelectorFromString(@"dealloc"));
Method repMethod = class_getInstanceMethod([self class], @selector(replaceDelloc));
method_exchangeImplementations(oriMethod, repMethod);
}
- (void)replaceDelloc{
NSLog(@"delloc被替換了");
}