method_exchangeImplementations运行时动态改变两个方法的实现
~~~
/**
* Exchanges the implementations of two methods.
*
* @param m1 Method to exchange with second method.
* @param m2 Method to exchange with first method.
*
* @note This is an atomic version of the following:
* \code
* IMP imp1 = method_getImplementation(m1);
* IMP imp2 = method_getImplementation(m2);
* method_setImplementation(m1, imp2);
* method_setImplementation(m2, imp1);
* \endcode
*/
OBJC_EXPORT void method_exchangeImplementations(Method m1, Method m2)
__OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);
~~~
代码:
~~~
- (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));
[self testExchange1];
[self testExchange2];
method_exchangeImplementations(m1, m2);
[self testExchange1];
[self testExchange2];
}
- (void) testExchange1 {
NSLog(@"%s", __func__);
}
- (void) testExchange2 {
NSLog(@"%s", __func__);
}
~~~
输出:
~~~
2015-11-02 13:38:40.264 02-runtime[2485:68367] -[ViewController testExchange1]
2015-11-02 13:38:40.266 02-runtime[2485:68367] -[ViewController testExchange2]
2015-11-02 13:38:40.281 02-runtime[2485:68367] -[ViewController testExchange2]
2015-11-02 13:38:40.281 02-runtime[2485:68367] -[ViewController testExchange1]
~~~
通过代码相信很容易理解吧
- 前言
- object_getIvar
- object_getClass
- object_getClassName
- object_setClass
- object_isClass
- object_setIvar
- objc_getClass
- Too many arguments to function call...
- objc_msgSend
- class_copyIvarList和class_copyMethodList
- method_exchangeImplementations
- 运用SEL,运行时改变两个方法的实现
- class_getInstanceMethod和class_getClassMethod
- class_respondsToSelector
- Objective-C Runtime 运行时之三:方法与消息