runtime 使用情况(一)

来源:互联网 发布:差不多先生 知乎 编辑:程序博客网 时间:2024/06/03 18:31

动态运行时添加方法,可能大家都知道,但是何时使用,可能不是很清楚。其中一种运用情况就是支持新旧两种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);}
0 0