我想在Objective C中测试方法调配:
1.在goodName
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
。任何部分都错了?感谢。
答案 0 :(得分:0)
你试图在AViewController中调用方法,但是你将代码放在+(void)load
中用于基础UIViewController。这是两个独立的类对象,因此您需要在+(void)load
中为AViewController执行此操作。