我想在 Objective C 中测试方法 swizzling:
goodName
1.添加方法AViewController
#import "AViewController.h"
#import "UIViewController+Tracking.h"
@interface AViewController ()
@end
@implementation AViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self goodName];
}
- (void) goodName {
NSLog(@"I am a good Name");
}
@end
2.添加调酒goodName
方法的类别。
#import "UIViewController+Tracking.h"
#import <objc/runtime.h>
#import "AViewController.h"
@implementation UIViewController (Tracking)
+ (void) load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(goodName);
SEL swizzledSelector = @selector(xxx_xxx_goodName);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
- (void)xxx_xxx_goodName {
NSLog(@"i am xxx goodName");
[self xxx_xxx_goodName];
}
@end
- 如果一切正常,
goodName
被调用的将输出i am xxx goodName
,但它是输出I am a good Name
。
有什么地方不对吗?谢谢。