runtime 使用情況(一)

動態運行時添加方法,可能大家都知道,但是何時使用,可能不是很清楚。其中一種運用情況就是支持新舊兩種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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章