先讲一下IMP函数入口:
//默认情况下,系统自带的IMP被定义为无参数无返回值的函数
/*重新定义IMP,有参数,带返回值和不带返回值*/
typedef void (*_VIMP) (id, SEL, ...);
typedef id(*_IMP) (id, SEL, ...);
void todoSomething(id yh_self, SEL name, ...){
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
/**为yh_self添加一个方法,其函数名为@selector(testDoSome:with:),函数实现为(IMP)invokeMethodForEffctive
*pagrm id 实例对象 yh_self
*pagrm SEL 方法指针 @selector(testDoSome:with:)
*pagrm IMP 函数入口 (IMP)invokeMethodForEffctive
*
*为一个实例添加一个没有的方法,然后执行这个方法
*/
class_addMethod([yh_self class], @selector(testDoSome:with:), (IMP)invokeMethodForEffctive, "v@:@i");
/*强制执行一个方法 1.用performSelector 去调用,有参数限制,最多两个*/
[yh_self performSelector:@selector(testDoSome:with:) withObject:@"adfas" withObject:@"1111"];
/*强制执行一个方法 2.转成IMP函数入口(相当于C语言的函数指针),然后直接调用IMP,无参数限制*/
Method m2 = class_getInstanceMethod([yh_self class], @selector(testDoSome:with:));
_VIMP balbal = (_VIMP)method_getImplementation(m2);
balbal(yh_self,@selector(testDoSome:with:),@"111",222);
/*强制执行一个方法 3.用NSInvocation类来调用,无参数限制*/
NSMethodSignature * methodSignature = [[yh_self class] instanceMethodSignatureForSelector:@selector(testDoSome:with:)];
NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
[invocation setTarget:yh_self];
[invocation setSelector:name];
NSString *a=@"111";
int b=2;
[invocation setArgument:&a atIndex:2];
[invocation setArgument:&b atIndex:3];
[invocation retainArguments];
[invocation invoke];
#pragma clang diagnostic pop
}
void invokeMethodForEffctive(id yh_self, SEL name, ...){
//todo
}
执行一个函数的3个非主流方法:
最新推荐文章于 2021-03-17 17:55:48 发布