有没有一种方法可以检索处理过UITouch的每个响应者?

3
我正在尝试调试游戏中的touchesBegan/Moved/Ended相关的减速问题;我认为我的某些触摸响应者没有正确卸载,因此随着游戏运行,越来越多的响应者会堆积起来,而触摸变得不那么灵敏,因为它们必须通过一个越来越大的响应者链传递。是否有一种方法可以查看/检索UITouch在移动过程中经过的路径?或者简单地检索所有活动响应者的列表?谢谢,-S
2个回答

5

您可以劫持 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() 是一件美妙的事情。当然要小心使用它;它非常适合调试,但如果不加区分地使用它,可能会非常令人困惑。


NSNotificationCenter自我 - zoul
@zoul。抱歉,这段代码来自NSNotificationCenter的劫持。很好发现。已修复。 - Rob Napier
这似乎无法在iOS 3.2上编译。声称_Method_不存在(以及您使用的其他反射函数)。有什么想法为什么会这样? - Aviad Ben Dov
请确保导入 <Foundation/NSObjCRuntime.h>。我会编辑答案以包含它。 - Rob Napier

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接