Authored by 孙凯

修改 tableview hook逻辑 review by daiqiang

... ... @@ -115,35 +115,22 @@ void yher_tableViewDidSelectRowAtIndexPath(id self, SEL _cmd, id tableView, NSIn
@try {
SEL swizzledMethodSEL = @selector(tableView:didSelectRowAtIndexPath:);
if (![delegate respondsToSelector:swizzledMethodSEL]) {
SEL originMethodSEL = @selector(collectionView:didSelectItemAtIndexPath:);
if (![delegate respondsToSelector:originMethodSEL]) {
return;
}
Class class = [delegate class];
Class delegateClass = [delegate class];
SEL originMethodSEL = NSSelectorFromString(@"yher_tableViewDidSelectRowAtIndexPath");
if (class_addMethod(class, originMethodSEL, (IMP)yher_tableViewDidSelectRowAtIndexPath, "v@:@@")) {
SEL swizzleMethodSEL = NSSelectorFromString(@"yher_tableViewDidSelectRowAtIndexPath");
Method dis_swizzledMethod = class_getInstanceMethod(class, swizzledMethodSEL);
Method originMethod = class_getInstanceMethod(delegateClass, originMethodSEL);
//若子类实现了swizzledMethodSEL,直接exchange;
//若子类没有实现时,读取父类的方法实现,再添加到子类上,
//如果添加成功,exchange实现,否则不交换
BOOL isLocal = [[self class] isLocallyDefinedMethod:dis_swizzledMethod onClass:class];
if (isLocal) {
Method dis_originMethod = class_getInstanceMethod(class, originMethodSEL);
method_exchangeImplementations(dis_originMethod, dis_swizzledMethod);
}else{
if (class_addMethod(class,
swizzledMethodSEL,
class_getMethodImplementation(class, swizzledMethodSEL),
method_getTypeEncoding(class_getInstanceMethod(class, swizzledMethodSEL)))) {
dis_swizzledMethod = class_getInstanceMethod(class, swizzledMethodSEL);
Method dis_originMethod = class_getInstanceMethod(class, originMethodSEL);
method_exchangeImplementations(dis_originMethod, dis_swizzledMethod);
}
}
Class class = GetSelectorInsClass(delegateClass,originMethodSEL,originMethod);
if (class_addMethod(class, swizzleMethodSEL, (IMP)yher_tableViewDidSelectRowAtIndexPath, "v@:@@")) {
Method swizzleMethod = class_getInstanceMethod(class, swizzleMethodSEL);
method_exchangeImplementations(originMethod, swizzleMethod);
}
} @catch (NSException *exception) {
... ... @@ -151,4 +138,16 @@ void yher_tableViewDidSelectRowAtIndexPath(id self, SEL _cmd, id tableView, NSIn
}
}
Class GetSelectorInsClass(Class hclass, SEL sel, Method sel_method) {
Class super_class = [hclass superclass];
if (!super_class) {
return hclass;
}
Method method = class_getInstanceMethod(super_class, sel);
if (method != sel_method) {
return hclass;
}
return GetSelectorInsClass(super_class, sel, sel_method);
}
@end
... ...