我的实现方案
```
@implementation UITableView (SMHook)
+ (void)load {
SEL fromSelector = @selector(setDelegate:);
SEL toSelector = @selector(sm_toDelegate:);
[SMHook hookClass:self fromSelector:fromSelector toSelector:toSelector];
}
- (void)sm_toDelegate:(id <UITableViewDelegate>)delegate {
[self sm_toDelegate:delegate];
// 得到代理对象,代理对象会调用代理方法
SEL fromSelector = @selector(tableView:didSelectRowAtIndexPath:);
SEL toSelector = @selector(sm_tableView:didSelectRowAtIndexPath:);
// 得到被替换的类的实例方式
Method fromMethod = class_getInstanceMethod(delegate.class, fromSelector);
// 得到替换的类的实例方法
Method toMethod = class_getInstanceMethod(self.class, toSelector);
// class_addMethod 添加要替换的方法
class_addMethod(delegate.class, toSelector, method_getImplementation(toMethod), method_getTypeEncoding(toMethod));
Method hookMethod = class_getInstanceMethod(delegate.class, toSelector);
method_exchangeImplementations(fromMethod, hookMethod);
}
-(void)sm_tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"aaa");
[self sm_tableView:tableView didSelectRowAtIndexPath:indexPath];
}
@end
```
展开