您可以劫持所需的方法UIResponder来添加日志记录,然后调用原始方法.这是一个例子:
#import <objc/runtime.h>
@interface UIResponder (MYHijack)
+ (void)hijack;
@end
@implementation UIResponder (MYHijack)
+ (void)hijackSelector:(SEL)originalSelector withSelector:(SEL)newSelector
{
Class class = [UIResponder class];
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method categoryMethod = class_getInstanceMethod(class, newSelector);
method_exchangeImplementations(originalMethod, categoryMethod);
}
+ (void)hijack
{
[self hijackSelector:@selector(touchesBegan:withEvent:) withSelector:@selector(MYHijack_touchesBegan:withEvent:)];
}
- (void)MYHijack_touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touches!");
[self MYHijack_touchesBegan:touches withEvent:event]; // Calls the original version of this method
}
@end
Run Code Online (Sandbox Code Playgroud)
然后在你的应用程序的某个地方(我有时把它放在main()自己),只需打电话[UIResponder hijack].只要UIResponder子类super在某个时刻调用,就会注入代码.
method_exchangeImplementations()是一件美丽的事.当然要小心; 它非常适合调试,但如果不加选择地使用它会非常混乱.
| 归档时间: |
|
| 查看次数: |
613 次 |
| 最近记录: |