NSInvocation

代码封装

// 封装invacation可以调用多个参数的方法
- (void)invacation
{
    //1.创建一个MethodSignature,签名中保存了方法的名称,参数和返回值
    //这个方法属于谁,那么就用谁来进行创建
    //注意:签名一般是用来设置参数和获得返回值的,和方法的调用没有太大的关系
    NSMethodSignature *signature = [ViewController instanceMethodSignatureForSelector:@selector(callWithNumber:andContext:withStatus:)];

    /*注意不要写错了方法名称
     //    NSMethodSignature *signature = [ViewController methodSignatureForSelector:@selector(call)];
     */

    //2.通过MethodSignature来创建一个NSInvocation
    //NSInvocation中保存了方法所属于的对象|方法名称|参数|返回值等等
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];

    /*2.1 设置invocation,来调用方法*/

    invocation.target = self;
    //    invocation.selector = @selector(call);
    //    invocation.selector = @selector(callWithNumber:);
    //    invocation.selector = @selector(callWithNumber:andContext:);
    invocation.selector = @selector(callWithNumber:andContext:withStatus:);

    NSString *number = @"10086";
    NSString *context = @"下课了";
    NSString *status = @"睡觉的时候";

    //注意:
    //1.自定义的参数索引从2开始,0和1已经被self and _cmd占用了
    //2.方法签名中保存的方法名称必须和调用的名称一致
    [invocation setArgument:&number atIndex:2];
    [invocation setArgument:&context atIndex:3];
    [invocation setArgument:&status atIndex:4];

    /*3.调用invok方法来执行*/
    [invocation invoke];
}

使用示例

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//     @[@"12"][2];
    NSNumber *number = @10;
    [self performSelector:@selector(demo) withObjects:@[number,@2.3]];

//    @try {
//         NSLog(@"---111111");
////        @[@"12"][2];
//         NSLog(@"---22222");
//    }
//    @catch (NSException *exception) {
//        NSLog(@"----333333");
//    }
//    @finally {
//           NSLog(@"---444444");
//    }
}

-(void)test1
{
    [self performSelector:@selector(abc) withObjects:nil];

    //   NSString *res = [self performSelector:@selector(callWithNumber:andContext:) withObjects:@[@"10086",@"2333",@"WC"]];
    //    NSLog(@"%@",res);

    //  NSString *res =   [self performSelector:@selector(demo) withObjects:nil];
    //    NSLog(@"%@",res);
}
-(void)test
{
    SEL selector = @selector(callWithNumber:andContext:withStatus:);

    //1.创建一个方法签名
    //不能直接使用methodSignatureForSelector方法来创建
    //1.需要告诉这个方法属于谁 ViewController
    //2.方法 SEL
    //方法的名称|参数个数
    NSMethodSignature *methodSignature = [ViewController instanceMethodSignatureForSelector:selector];

    //2.创建NSInvocation
    //要传递方法签名
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
    invocation.target = self;
    invocation.selector = selector;

    //设置参数
    NSString *number = @"10086";
    //self and _cmd 0~1
    [invocation setArgument:&number atIndex:2];

    NSString *love = @"love";
    [invocation setArgument:&love atIndex:3];

    NSString *status = @"WC";
    [invocation setArgument:&status atIndex:4];
    //3.调用该方法
    [invocation invoke];

}

你可能感兴趣的:(NSInvocation)