runtime-class_addMethod\objc_msgSend\NSInvocation

来源:互联网 发布:.love域名 编辑:程序博客网 时间:2024/05/16 10:47
#import <objc/runtime.h>

#import <objc/message.h>


  TestClass *instance = [[TestClass alloc]init];    //给testclass添加一个fun    class_addMethod([TestClass class],@selector(ocMethodA::), (IMP)cfunctionA,"@@:@@");                if ([instance respondsToSelector:@selector(ocMethodA::)]) {                NSLog(@"Yes, instance respondsToSelector:@selector(ocMethodA::)");        NSString *myString = @"我是一个OC的method,C函数实现";        NSString *myString2 = @"-----我是第二个参数";                        //方法1        objc_msgSend(instance, @selector(ocMethodA::),myString,myString2);                        //方法2        SEL mySelector = @selector(ocMethodA::);        NSMethodSignature * sig = [[TestClass class]  instanceMethodSignatureForSelector: mySelector];        NSInvocation * myInvocation = [NSInvocation invocationWithMethodSignature: sig];        [myInvocation setTarget: instance];//0        [myInvocation setSelector: mySelector];//1        [myInvocation setArgument: &myString atIndex: 2];        [myInvocation setArgument: &myString2 atIndex: 3];        NSString* result = nil;        [myInvocation retainArguments];        [myInvocation invoke];        [myInvocation getReturnValue: &result];        NSLog(@"The NSInvocation invoke string is: %@", result);            }    else    {                NSLog(@"Sorry");            }

NSString* cfunctionA(id self, SEL _cmd, NSString *str, NSString *str1) {        NSLog(@"%@%@", str,str1);        return @"结果返回";//随便返回个值    }



 




0 0
原创粉丝点击