您的位置:首页 > 移动开发 > IOS开发

运用SEL,运行时改变两个方法的实现

2015-11-02 13:57 411 查看
直接上代码:

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

Method m1 = class_getInstanceMethod([self class], @selector(testExchange1));

Method m2 = class_getInstanceMethod([self class], @selector(testExchange2));

IMP impM1 = method_getImplementation(m1);

IMP impM2 = method_getImplementation(m2);

[self testExchange1];

[self testExchange2];

method_setImplementation(m2, impM1);

method_setImplementation(m1, impM2);

[self testExchange1];

[self testExchange2];
}

- (void) testExchange1 {
NSLog(@"%s", __func__);
}
- (void) testExchange2 {
NSLog(@"%s", __func__);
}


输出:

2015-11-02 13:54:12.646 02-runtime[2592:71972] -[ViewController testExchange1]
2015-11-02 13:54:12.647 02-runtime[2592:71972] -[ViewController testExchange2]
2015-11-02 13:54:12.648 02-runtime[2592:71972] -[ViewController testExchange2]
2015-11-02 13:54:12.649 02-runtime[2592:71972] -[ViewController testExchange1]


另外还可以用method_exchangeImplementations  运行时交换两个方法的实现,原文链接请点击
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息