繁体   English   中英

方法是否可能在静态库中混乱?

[英]Is Method swizzling in a static library possible?

我试图创建一个自动UI日志记录,我发现方法混乱是解决该问题的一种非常好的方法。 我试过了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。 我现在正在尝试不同的代码位置,以查看它何时起作用,何时不起作用。

Apple文档中获取有关load方法的信息

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

初始化的顺序如下:

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

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

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

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

此外:

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

  • 类+ load方法在类自己的+ load方法之后被调用。

因此,即使在静态库中,方法转换也不是问题,因为此时链接到框架的类已经加载。 method_exchangeImplementations应该可以按预期工作。 看来问题出在别的地方。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM