Iphone 有没有办法在UIApplication中的-sendAction:to:from:forEvent:中挂起一些代码?

Iphone 有没有办法在UIApplication中的-sendAction:to:from:forEvent:中挂起一些代码?,iphone,events,Iphone,Events,我怎么能这么做?我想捕捉这些事件,看看整个应用程序中发生了什么。我必须为那个应用程序创建子类吗 UIControl在事件发生时调用此方法。似乎如果我将UIControl子类化,就没有一点可以让我深入了解事件的细节。我可以只指定那些事件掩码,并使用(id)sender参数调用一些选择器,但这样,我就看不到触摸坐标之类的东西了。您可以使用方法swizzling,并提供自己的实现 @implementaion UIApplication (MyStuff) - (BOOL)_my_sendAction

我怎么能这么做?我想捕捉这些事件,看看整个应用程序中发生了什么。我必须为那个应用程序创建子类吗


UIControl在事件发生时调用此方法。似乎如果我将UIControl子类化,就没有一点可以让我深入了解事件的细节。我可以只指定那些事件掩码,并使用(id)sender参数调用一些选择器,但这样,我就看不到触摸坐标之类的东西了。

您可以使用方法swizzling,并提供自己的实现

@implementaion UIApplication (MyStuff)
- (BOOL)_my_sendAction:(SEL)action to:(id)target from:(id)sender forEvent:(UIEvent *)event
{
    // do your stuff here
    // ...

    // call original selector
    [self _orig_sendAction:action to:target from:sender forEvent:event];
}
@end


BOOL DTRenameSelector(Class _class, SEL _oldSelector, SEL _newSelector)
{
    Method method = nil;

    // First, look for the methods
    method = class_getInstanceMethod(_class, _oldSelector);
    if (method == nil)
        return NO;

    method->method_name = _newSelector;
    return YES;
}
您只需在应用程序立即启动时交换两个选择器:

Class UIApplicationCls = objc_getClass("UIApplication");
DTRenameSelector(UIApplicationCls, @selector(sendAction:to:from:forEvent:), @selector(_orig_sendAction:to:from:forEvent:);
DTRenameSelector(UIApplicationCls, @selector(_my_sendAction:to:from:forEvent:), @selector(sendAction:to:from:forEvent:);

您是否尝试过向UIApplication添加类别或扩展,并提供-sendAction:to:from:forEvent:?fyi method->method\u name的实现?我认为swizzling对于现代运行时来说是个坏主意。您仍然应该能够将UIApplication子类化: