【发布时间】:2016-03-07 12:30:48
【问题描述】:
我正在尝试创建一个自动 UI 日志记录,我发现方法 swizzling 是一个非常好的解决问题的方法。我试图调配UIApplication 实现的sendAction 方法。
我的问题是有时有效,有时无效。特别是如果我在静态库中编写代码,将其导出到 .a 文件并在我的项目中使用它。
如果在静态库中实现方法调配是否会成为问题?
即使在代码中,它有时也能正常工作,有时什么也没有发生。它总是进入
load方法,但并不总是进入heap_sendAction方法。
代码如下:
#import <objc/runtime.h>
@implementation UIApplication (EventAutomator)
+ (void)load
{
Class class = [self class];
SEL originalSelector = @selector(sendAction:to:from:forEvent:);
SEL replacementSelector = @selector(heap_sendAction:to:from:forEvent:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method replacementMethod = class_getInstanceMethod(class, replacementSelector);
method_exchangeImplementations(originalMethod, replacementMethod);
}
- (BOOL)heap_sendAction:(SEL)action to:(id)target from:(id)sender forEvent:(UIEvent *)event
{
NSString *selectorName = NSStringFromSelector(action);
printf("Selector %s occurred.\n", [selectorName UTF8String]);
return [self heap_sendAction:action to:target from:sender forEvent:event];
}
@end
----- 更新----:
当我将函数放在 viewcontroller.m 类中时,会调用 heap_sendAction。 我现在正在尝试不同的代码位置,看看它何时有效,何时无效。
【问题讨论】:
-
请提供更多信息,在哪些情况下
heap_sendAction被调用,在哪些情况下未被调用。这完全是随机的吗?点击按钮?何时从代码中显式调用方法?其他情况? -
更新了原始消息。
标签: objective-c logging automation click method-swizzling