首先創(chuàng)建一個(gè)初始化工程壮啊,創(chuàng)建 HQViewController
,在 HQViewController
中加入一個(gè) log
方法冒版,如下:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
}
- (void)log{
NSLog(@"HQtest1");
}
然后創(chuàng)建一個(gè)子類(lèi)HQSubViewController
,重寫(xiě) log
方法中并在方法中實(shí)現(xiàn)調(diào)用原方法代碼,如下:
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)log{
NSLog(@"HQtest2");
struct objc_super superClass = {
.receiver = self,
.super_class = class_getSuperclass(object_getClass(self))
};
// 調(diào)用原來(lái)的方法
void (*objc_msgSendSuperClass)(void *,SEL) = (void *)objc_msgSendSuper;
objc_msgSendSuperClass(&superClass,_cmd);
// _cmd在Objective-C的方法中表示當(dāng)前方法的selector
}
再創(chuàng)建一個(gè) NSObject
的 Category
負(fù)責(zé)進(jìn)行方法交換绘雁,將原對(duì)象的 isa
指針指向該對(duì)象類(lèi)的子類(lèi)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];
// 將原類(lèi)中的isa指針指向 子類(lèi)
object_setClass(instance, newClass);
}
@end
最后在 ViewControlller
中進(jìn)行測(cè)試即可票彪,此時(shí)的 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
打印結(jié)果如下:
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