iOS NSIvocation的简介与使用

来源:互联网 发布:土木工程翻译软件 编辑:程序博客网 时间:2024/06/06 02:36

一、简介

NsInvocation 主要是为完成,调用某个对象的方法 ,进行使用的;(通常是因为这个对象的方法没有Api)


二、使用方式

Nsivlcation 的功能较为强大,可以传值多个参数;

在.m 文件中的代码



- (void)viewDidLoad {

    [superviewDidLoad];

    

    

    //NSMethodSignature生成的签名第一个参数传的是你要调用的类,第二个参数是在类中实现的方法(方法不在.h文件中声明也没有关系)

    SEL seclector =NSSelectorFromString(@"changeName:withtype:");

    NSMethodSignature * signature = [ViewControllerinstanceMethodSignatureForSelector:seclector];

    

    //创建NSInvocation第一个参数传的是签名

    NSInvocation * vocation = [NSInvocationinvocationWithMethodSignature:signature];

    

    //target传的是你想要调用的类必须与生成签名的时候一致

    vocation.target =self;

    

    //voation中的方法必须和签名中的方法一致

    vocation.selector = seclector;

    

  

    //参数的传递

    NSString * name =@"郭晓广";

    

    //设置参数的时候不能从0开始,因为0已经被self占用,1已经被_cmd占用只能从2开始

    [vocation setArgument:&nameatIndex:2];

   

    //同上

    NSString * type =@" 啊啊啊啊";

    [vocation setArgument:&typeatIndex:3];

    

    //只要调用invocationinvoke方法,就代表执行nsivocation对象中制定对象的指定方法

    [vocation invoke];


}

-(void)changeName:(NSString * )name withtype:(NSString*)type

{

    NSLog(@"改变名字%@%@",name,type);

}










0 0
原创粉丝点击