首先创建一个初始化工程,创建 HQViewController
,在 HQViewController
中加入一个 log
方法,如下:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
}
- (void)log{
NSLog(@"HQtest1");
}
然后创建一个子类HQSubViewController
,重写 log
方法中并在方法中实现调用原方法代码,如下:
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)log{
NSLog(@"HQtest2");
struct objc_super superClass = {
.receiver = self,
.super_class = class_getSuperclass(object_getClass(self))
};
// 调用原来的方法
void (*objc_msgSendSuperClass)(void *,SEL) = (void *)objc_msgSendSuper;
objc_msgSendSuperClass(&superClass,_cmd);
// _cmd在Objective-C的方法中表示当前方法的selector
}
再创建一个 NSObject
的 Category
负责进行方法交换,将原对象的 isa
指针指向该对象类的子类HQSubViewController
:
@implementation NSObject (ChangeM)
+ (void)changeInstance:(NSObject *)instance method:(SEL)selector{
Method oldMethod = class_getInstanceMethod([instance class], selector);
if (!oldMethod) {
NSLog(@"方法不存在");
return;
}
Class newClass = [HQSubViewController class];
// 将原类中的isa指针指向 子类
object_setClass(instance, newClass);
}
@end
最后在 ViewControlller
中进行测试即可,此时的 ViewController 代码如下:
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
HQViewController *viewC1 = [[HQViewController alloc]init];
[viewC1 log];
HQViewController *viewC2 = [[HQViewController alloc]init];
[HQViewController changeInstance:viewC2 method:@selector(log)];
[viewC2 log];
}
@end
打印结果如下:
2017-03-28 11:51:44.288 HQChangeMethod[10862:625765] HQtest1
2017-03-28 11:51:44.289 HQChangeMethod[10862:625765] HQtest2
2017-03-28 11:51:44.289 HQChangeMethod[10862:625765] HQtest1
网友评论