动态解析实例方法
void walk(){
NSLog(@"%s",__func__);
}
+ (BOOL)resolveInstanceMethod:(SEL)sel{
//方法未实现
// if (sel == @selector(walk)) {
// //返回c方法实现
// return class_addMethod(self, sel, (IMP)walk, "v@:");
// }
//方法未实现
if(sel ==@selector(walk)) {
//获取方法
Method method = class_getInstanceMethod(self,@selector(run));
//获取方法的实现
IMP methodIMP = method_getImplementation(method);
//修改方法的实现
// v:方法返回值
//@:方法名,: :方法参数 ,a: 固定
returnclass_addMethod(self, sel, methodIMP,"v@:");
}
return [super resolveInstanceMethod:sel];
}
- (void)run{
NSLog(@"%s",__func__);
}
动态解析类方法
//类方法动态解析
+ (BOOL)resolveClassMethod:(SEL)sel{
//jump方法未实现
if(sel == @selector(jump)) {
//获取类方法
Method method = class_getClassMethod(self,@selector(talk));
//方法实现
IMP methodIMP = method_getImplementation(method);
//替换方法的实现
return class_addMethod(object_getClass(self), sel, methodIMP,"v@:");
}
return [super resolveClassMethod:sel];
}
+ (void)talk{
NSLog(@"%s",__func__);
}
方法签名
- (NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector{
//对run方法签名
if(aSelector ==@selector(run)){
return [NSMethodSignature signatureWithObjCTypes:"v@:"];
}
return [super methodSignatureForSelector:aSelector];
}
- (void)forwardInvocation:(NSInvocation*)anInvocation{
//把消息转发给ZFDog处理
// [anInvocation invokeWithTarget:[ZFDog new]];
//转发自己处理
anInvocation.selector=@selector(jump);
[anInvocation invoke];
}
- (void)jump{
NSLog(@"%s",__func__);
}
默认先走动态解析,如果动态解析未处理,则走快速转发;若快速转发未处理,则走方法签名
网友评论