我正在学习在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。
答案 0 :(得分:1)
您使用的是正确的方法吗?
向具有给定名称和实现的类添加新方法。 class_addMethod将添加超类的实现的覆盖, 但不会替换此类中的现有实现。至 更改现有实现,使用method_setImplementation。
此方法返回:
如果成功添加方法,则为YES,否则为NO(例如, 该类已包含具有该名称的方法实现。)