关于Method Swizzling,有位大神介绍的很详细了,地址:Objective-C的hook方案(一): Method Swizzling
其实呢,菜逼一个的我不怎么懂,就把我项目中用到的贴上来吧:
代码:(写在NSObject的类别里 需要引入#import <objc/runtime.h>)
@implementation NSObject (Swizzle)
+ (void)swizzleMethod:(SEL)srcSel tarSel:(SEL)tarSel {
Class clazz = [self class];
[self swizzleMethod:clazz srcSel:srcSel tarClass:clazz tarSel:tarSel];
}
+ (void)swizzleMethod:(SEL)srcSel tarClass:(NSString *)tarClassName tarSel:(SEL)tarSel {
if (!tarClassName) {
return;
}
Class srcClass = [self class];
Class tarClass = NSClassFromString(tarClassName);
[self swizzleMethod:srcClass srcSel:srcSel tarClass:tarClass tarSel:tarSel];
}
+ (void)swizzleMethod:(Class)srcClass srcSel:(SEL)srcSel tarClass:(Class)tarClass tarSel:(SEL)tarSel {
if (!srcClass) {
return;
}
if (!srcSel) {
return;
}
if (!tarClass) {
return;
}
if (!tarSel) {
return;
}
XSD_TRY_BODY(Method srcMethod = class_getInstanceMethod(srcClass,srcSel);
Method tarMethod = class_getInstanceMethod(tarClass,tarSel);
method_exchangeImplementations(srcMethod, tarMethod);)
}
@end
其中的宏定义:
#define XSD_TRY_BODY(__target) \
@try {\
{__target}\
}\
@catch (NSException *exception) {\
NSLog(@"exception ===== %@", [exception description]);\
}\
@finally {\
\
}
用法:
#import "MWPhotoBrowser+XSDExt.h"
@implementation MWPhotoBrowser (XSDExt)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self swizzleMethod:@selector(_toggleControls) tarSel:@selector(toggleControls)];
});
}
- (void)_toggleControls {
[self.navigationController popViewControllerAnimated:YES];
}
@end
我这是用到了一个浏览图片的第三方库,想改其中的一个方法,直接写了一个方法,在load方法里写了替换的方法;