动态运行时添加方法,可能大家都知道,但是何时使用,可能不是很清楚。其中一种运用情况就是支持新旧两种API。
- (void)doSomething {
// legacy code goes here...
}
- (void)doSomethingWithNewAPI {
// do the same thing, but use new API.
}
+ (void)initialise {
//check self
if (self != [MyObject class])
return;
//check if support newAPI
if ([[SomeSystemClass instancesResponsedToSelector:@selector(theNewAPI)] == NO)]
return;
Method legacy = class_getInstanceMethod(self, @selector(doSomething));
Method newAPI = class_getInstanceMethod(self, @selector(doSomethingWithNewAPI));
//change two methods
method_exchangeImplementations(legacy, newAPI);
}