-
Method Swizzling 即在運行期間交換方法實現。
例如下面例子:
- (void) method1 {
NSLog(@"method1");
}
- (void) method2 {
NSLog(@"method2");
}
-(void)methodExchange
{
Method method1 = class_getInstanceMethod([self class], @selector(method1));
Method method2 = class_getInstanceMethod([self class], @selector(method2));
//交換method1和method2的IMP指針,(IMP代表了方法的具體的實現)
method_exchangeImplementations(method1, method2);
}
執行調用:
[self methodExchange];
[self method1];
[self method2];
最后打印:
method2
method1
-
應用場景
Method Swizzling的使用場景可以在分類中修改原類的方法實現。例如在MJRefresh中,實現了每次執行完UIScrollView自己的方法reloadData后執行[self executeReloadDataBlock]。
@implementation UITableView (MJRefresh)
+ (void)load
{
[self exchangeInstanceMethod1:@selector(reloadData) method2:@selector(mj_reloadData)];
}
- (void)mj_reloadData
{
[self mj_reloadData];
[self executeReloadDataBlock];
}
@end
參考文檔:
輕松學習之 IMP指針的作用