【问题标题】:Method swizzling in Objective C [duplicate]Objective C中的方法调配[重复]
【发布时间】:2017-07-16 13:19:28
【问题描述】:

我正在学习在 Objective C 中调配的方法。下面是我调配的代码

+(void)load{
NSLog(@"Load %@",[self class]);

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{

    Class class = [self class];

    SEL originalSelector = @selector(viewWillAppear:);
    SEL swizzlingSelector = @selector(logging_viewWillAppear:);

    Method origialMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzlingMethod = class_getInstanceMethod(class, swizzlingSelector);



    BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzlingMethod), method_getTypeEncoding(swizzlingMethod));

    if (didAddMethod) {
        class_replaceMethod(class, swizzlingSelector, method_getImplementation(origialMethod), method_getTypeEncoding(origialMethod));
    }
    else{
        method_exchangeImplementations(origialMethod, swizzlingMethod);
    }
});
}

-(void)logging_viewWillAppear:(BOOL)animated{
[self logging_viewWillAppear:animated];
NSLog(@"Logging viewWillAppear");
}

一切正常。但是 BOOL didAddMethod 总是返回 NO。我想了解我们将得到 didAddMethod = YES 的场景是什么。

【问题讨论】:

    标签: objective-c swizzling


    【解决方案1】:

    你是否使用了正确的方法?

    向具有给定名称和实现的类添加新方法。 class_addMethod 将添加超类实现的覆盖, 但不会替换此类中的现有实现。至 更改现有实现,使用 method_setImplementation。

    这个方法返回:

    如果方法添加成功则为YES,否则为NO(例如, 该类已包含具有该名称的方法实现)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 2014-11-13
      相关资源
      最近更新 更多