一丶使用場(chǎng)景
修改第三方庫(kù)的代碼,hook太復(fù)雜,直接寫(xiě)個(gè)B類;重定向,修改源碼;
完美
二丶具體實(shí)施
A類
@interface ZBAAAA : NSObject
@end
@implementation ZBAAAA
@end
B類
@interface ZBBBBB : NSObject
- (void)bbbb;
@end
@implementation ZBBBBB
//必須實(shí)現(xiàn)
- (instancetype)alloc
{
return [[self class] alloc];
}
- (void)bbbb
{
NSLog(@"%s",__func__);
}
@end
結(jié)果:
三丶解釋
知識(shí)點(diǎn):
isa機(jī)制圖
- (NSArray *)NSObjectMetaMethodList {
u_int count;
NSMutableArray *methodList = [NSMutableArray array];
Class metaClass = objc_getMetaClass([@"NSObject" UTF8String]);
Method *methods = class_copyMethodList(metaClass, &count);
for (int i = 0; i < count; i++) {
SEL name = method_getName(methods[i]);
NSString *strName = [NSString stringWithCString:sel_getName(name)
encoding:NSUTF8StringEncoding];
[methodList addObject:strName];
}
free(methods);
return methodList;
}
- (NSArray *)methodList {
u_int count;
NSMutableArray *methodList = [NSMutableArray array];
Method *methods = class_copyMethodList([self class], &count);
for (int i = 0; i < count; i++) {
SEL name = method_getName(methods[i]);
NSString *strName = [NSString stringWithCString:sel_getName(name)
encoding:NSUTF8StringEncoding];
[methodList addObject:strName];
}
free(methods);
return methodList;
}
首先,alloc方法是在NSObject的meta類里;
[ZBAAAA alloc]
通過(guò)object_setClass
[ZBAAAA alloc]變成
本來(lái)Aclass 的isa 會(huì)到 AMeta里面去找,最終到root meta class 里面找到alloc;
重定向B之后
Aclass 的isa 會(huì)到 Bclass里面去找,最終到B root class (NSObject);NSObject里面壓根沒(méi)有alloc;
所以需要
@implementation ZBBBBB
//必須實(shí)現(xiàn)
- (instancetype)alloc
{
return [[self class] alloc];
}
- (void)bbbb
{
NSLog(@"%s",__func__);
}
@end