Pro*_*ber 6 objective-c swizzling ios objective-c-category method-swizzling
我试着弄清楚事情是如何运作的.所以我想当我用类别覆盖某些方法时,我会得到有趣的NSLogs.
@implementation UIView(Learning)
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
NSLog(@"-hitTest:withEvent: event=%@", event);
return [self hitTest:point withEvent:event];
}
@end
Run Code Online (Sandbox Code Playgroud)
超级和自我在这里不起作用.有没有办法调用-hitTest的原始实现:withEvent:?我想要的是NSLog每次-hitTest:withEvent:在UIView上调用.
这仅用于个人学习目的.我希望看到活动的实施.
Dav*_*ong 15
你可以这样做,但不能使用类别.类别替换方法.(警告,汽车比喻)如果你有一辆汽车,并且你摧毁了那辆汽车并用一辆新车取代它,你还能使用旧车吗?不,因为它消失了,不再存在了.与类别相同.
你可以做的是使用Objective-C运行时在运行时使用不同的名称来添加方法(比如," bogusHitTest:withEvent:"),然后交换的实现hitTest:withEvent:和bogusHitTest:withEvent:.这样,当代码调用时hitTest:withEvent:,它将执行最初编写的代码bogusHitTest:withEvent:.然后,您可以调用该代码bogusHitTest:withEvent:,这将执行原始实现.
所以伪造的方法看起来像:
- (UIView *) bogusHitTest:(CGPoint)point withEvent:(UIEvent *)event {
NSLog(@"executing: %@", NSStringFromSelector(_cmd));
return [self bogusHitTest:point withEvent:event];
}
Run Code Online (Sandbox Code Playgroud)
交换方法的代码将是:
Method bogusHitTest = class_getInstanceMethod([UIView class], @selector(bogusHitTest:withEvent:));
Method hitTest = class_getInstanceMethod([UIView class], @selector(hitTest:withEvent:));
method_exchangeImplementations(bogusHitTest, hitTest);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4263 次 |
| 最近记录: |