目的のメソッドをハイジャックして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
次に、アプリのどこか (私は時々main()
それ自体に入れます) を呼び出すだけ[UIResponder hijack]
です。UIResponder
ある時点でサブクラスが呼び出される限りsuper
、コードが挿入されます。
method_exchangeImplementations()
美しいものです。もちろん注意してください。デバッグには最適ですが、無差別に使用すると非常に混乱します。