【问题标题】:Is Method swizzling in a static library possible?静态库中的 Method swizzling 是否可能?
【发布时间】:2016-03-07 12:30:48
【问题描述】:

我正在尝试创建一个自动 UI 日志记录,我发现方法 swizzling 是一个非常好的解决问题的方法。我试图调配UIApplication 实现的sendAction 方法。

我的问题是有时有效,有时无效。特别是如果我在静态库中编写代码,将其导出到 .a 文件并在我的项目中使用它。

  1. 如果在静态库中实现方法调配是否会成为问题?

  2. 即使在代码中,它有时也能正常工作,有时什么也没有发生。它总是进入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


【解决方案1】:

来自Apple documentation regarding load method

加载消息被发送到既是 动态加载和静态链接,但前提是新加载的 类或类别实现了可以响应的方法。

初始化顺序如下:

  1. 您链接到的任何框架中的所有初始化程序。

  2. 图像中的所有 +load 方法。

  3. 图像中的所有 C++ 静态初始化程序和 C/C++ 属性(构造函数)函数。

  4. 链接到您的框架中的所有初始化程序。

另外:

  • 一个类的 +load 方法在其所有超类的 +load 方法之后被调用。

  • 在类自己的+load方法之后调用一个类别的+load方法。

因此,即使在静态库中,方法调配也不是问题,因为此时您链接到的框架中的类已经加载。 method_exchangeImplementations 应该按预期工作。看起来问题出在其他地方。

【讨论】:

  • 正如我所提到的,“加载”方法已正确实施并且始终有效。我的问题是第二部分,有时有效,有时无效......我不知道在哪里寻找错误。它是一个非常简单的代码块,我应该寻找任何线索吗?也许在“加载”方法中执行的代码在某个时刻被覆盖了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
  • 1970-01-01
  • 2012-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多