iOS NSInvocation用法简介

来源:互联网 发布:seo常用外链资源整理 编辑:程序博客网 时间:2024/05/22 01:57

在 iOS中可以直接调用某个对象的消息方式有两种:

一种是performSelector:withObject;

再一种就是NSInvocation。

第一种方式比较简单,能完成简单的调用。但是对于>2个的参数或者有返回值的处理,那就需要做些额外工作才能搞定。那么在这种情况下,我们就可以使用NSInvocation来进行这些相对复杂的操作。

//test performSelector      注意:此种方法只使用于最多两个参数,多个参数无能为力
- (void)testMutiParams {
   
//test perform
   
NSString *strRe = [self performSelector:@selector(appendString:String2:)withObject:@"hello"withObject:@"world"];
   
NSLog(@"strRe :%@",strRe);
   
   
//question ?
   
NSString *strRe1 = [self performSelector:@selector(appendString:String2:String3:)withObject:@"hello"withObject:@"world"];
   
NSLog(@"strRe :%@",strRe1);

   
NSString *strMy1 = @"My string1";
   
NSString *strMy2 = @"My string2";
   
NSString *strMy3 = @"My string3";
   
   
SEL mySelector = @selector(appendString:String2:String3:);
   
NSMethodSignature*sig = [[selfclass]instanceMethodSignatureForSelector:mySelector];
   
   
NSInvocation *myInvocation = [NSInvocationinvocationWithMethodSignature:sig];
    [myInvocation
setTarget:self];
    [myInvocation
setSelector:mySelector];
    [myInvocation
setArgument:&strMy1atIndex:2];
    [myInvocation
setArgument:&strMy2atIndex:3];
    [myInvocation
setArgument:&strMy3atIndex:4];
   
   
NSString *strResult = nil;
    [myInvocation
retainArguments];
    [myInvocation
invoke];
    [myInvocation
getReturnValue:&strResult];
   
NSLog(@"The NSInvocation invoke string is :%@",strResult);

}

- (NSString*)appendString:(NSString*)str1 String2:(NSString*)str2 String3:(NSString*)str3 {
   
return [NSString stringWithFormat:@"%@,%@,%@",str1,str2,str3];
}







- (void)testInvocation {
   MyClass *myClass = [[MyClassalloc]init];
   
NSString *strMy = @"My string";
   
   
//common selector
   
NSString *normalInvokeString = [myClass appendMyString:strMy];
   
NSLog(@"The normal invoke string is :%@",normalInvokeString);
   
   
//NSInvocation selector
   
SEL mySelector = @selector(appendMyString:);
   
NSMethodSignature*sig = [[myClass class]instanceMethodSignatureForSelector:mySelector];
   
   
NSInvocation *myInvocation = [NSInvocationinvocationWithMethodSignature:sig];
    [myInvocation
setTarget:myClass];
    [myInvocation
setSelector:mySelector];
    [myInvocation
setArgument:&strMyatIndex:2];
   
   
NSString *strResult = nil;
    [myInvocation
retainArguments];
    [myInvocation
invoke];
    [myInvocation
getReturnValue:&strResult];
   
NSLog(@"The NSInvocation invoke string is :%@",strResult);
 

}

类实现:

#import<Foundation/Foundation.h>

@interface MyClass : NSObject

- (
NSString *)appendMyString:(NSString*)string;

@end

#import"MyClass.h"

@implementation MyClass

- (
NSString *)appendMyString:(NSString*)string {
   
NSString *mString = [NSStringstringWithFormat:@"%@ after append method", string];
   
return mString;
}

@end


这里说明一下[myInvocation setArgument: &myString atIndex: 2];为什么index从2开始 ,原因为:0 1 两个参数已经被target 和selector占用。

0 0
原创粉丝点击