这两种调酒方式略有不同。我只想澄清他们之间是否存在根本不同或错误
假设我们正在viewDidLoad
调动UIView
第一种方式(使用class_addMethod
):
@implementation UIView (SwizzleFirstWay)
+ (void)load {
SEL originalSelector = @selector(viewDidLoad);
SEL swizzledSelector = @selector(swizzled_viewDidLoad);
Method originalMethod = class_getInstanceMethod(self, originalSelector);
Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
class_addMethod(self,
originalSelector,
class_getMethodImplementation(self, originalSelector),
method_getTypeEncoding(originalMethod));
// Adding the method
class_addMethod(self,
swizzledSelector,
class_getMethodImplementation(self, swizzledSelector),
method_getTypeEncoding(swizzledMethod));
method_exchangeImplementations(originalMethod, swizzledMethod);
}
+ (void)swizzled_viewDidLoad {
// ... the swizzled implementation
// ...
// ...
[self swizzled_viewDidLoad]; // calling back to the original implementation
}
@end
第二种方式(不使用class_addMethod
):
+ (void)load {
SEL originalSelector = @selector(viewDidLoad);
SEL swizzledSelector = @selector(swizzled_viewDidLoad);
Method originalMethod = class_getInstanceMethod(self, originalSelector);
Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
// NOT USING class_addMethod
method_exchangeImplementations(originalMethod, swizzledMethod);
}
+ (void)swizzled_viewDidLoad {
// ... the swizzled implementation
// ...
// ...
[self swizzled_viewDidLoad]; // calling back to the original implementation
}
@end