zoukankan      html  css  js  c++  java
  • NSMethodSignature和NSInvocation的使用(方法传多参数)

    动态调用方法时会用到,例子 

    -(NSString *)myMethod:(NSString *)param1 withParam2:(NSNumber *)param2 

        NSString *result = @"objc"; 
        NSLog(@"par = %@",param1); 
        NSLog(@"par 2 = %@",param2); 
        return result; 

    -(void)invokeMyMethodDynamically 

        SEL selector = @selector(myMethod:withParam2:); 
        NSMethodSignature *methodSignature = [[self class] instanceMethodSignatureForSelector:selector];//获得类和方法的签名 
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature]; 
        //从签名获得调用对象 
        [invocation setTarget:self]; 
        //设置target 
        [invocation setSelector:selector];//设置selector 
        NSString *returnValue = nil; 
        NSString *argument1 = @"fist"; 
        NSNumber *argument2 = [NSNumber numberWithInt:102]; 
        [invocation setArgument:&argument1 atIndex:2];//设置参数,第一个参数index为2 
        [invocation setArgument:&argument2 atIndex:3]; 
        [invocation retainArguments];//retain一遍参数 
        [invocation invoke];//调用 
        [invocation getReturnValue:&returnValue];//得到返回值,此时不会再调用,只是返回值 
        NSLog(@"return value = %@",returnValue); 

  • 相关阅读:
    第11组 团队Git现场编程实战
    第11组 团队项目-需求分析报告
    团队项目-选题报告
    第二次结对编程作业
    第11组 团队展示
    第一次结对编程作业
    Nginx学习笔记
    Git学习笔记
    Qt学习笔记
    Eclipse中Outline里各种图标的含义
  • 原文地址:https://www.cnblogs.com/swallow37/p/4435670.html
Copyright © 2011-2022 走看看