-
Method Swizzling 即在運行期間交換方法實現(xiàn)。
例如下面例子:
- (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代表了方法的具體的實現(xiàn))
method_exchangeImplementations(method1, method2);
}
執(zhí)行調(diào)用:
[self methodExchange];
[self method1];
[self method2];
最后打游∩场:
method2
method1
-
應(yīng)用場景
Method Swizzling的使用場景可以在分類中修改原類的方法實現(xiàn)。例如在MJRefresh中荷鼠,實現(xiàn)了每次執(zhí)行完UIScrollView自己的方法reloadData后執(zhí)行[self executeReloadDataBlock]句携。
@implementation UITableView (MJRefresh)
+ (void)load
{
[self exchangeInstanceMethod1:@selector(reloadData) method2:@selector(mj_reloadData)];
}
- (void)mj_reloadData
{
[self mj_reloadData];
[self executeReloadDataBlock];
}
@end
參考文檔:
輕松學(xué)習(xí)之 IMP指針的作用