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

来源:互联网 发布:c语言输出*等腰三角形 编辑:程序博客网 时间:2024/06/03 08:37


直接上代码:

- (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  运行时交换两个方法的实现,原文链接请点击


0 0
原创粉丝点击