您的位置:首页 > 其它

关于NSInvocation-Tagert事件的多个参数实现方法

2015-01-12 17:48 190 查看
在iOS直接调用某个对象的消息是方法有两种:

一:performselector:withObject:

二:invocation

第一种方式比较简单,能完成简单的调用。但是对于>2个的参数或者有返回值的处理,可以使用NSInvocation来进行这些相对复杂的操作

NSInvocation可以处理参数、返回值。会java的人都知道反射操作,其实NSInvocation就相当于反射操作。

main.h

[html] view
plaincopy

#import <Foundation/Foundation.h>

#import "MyClass.h"

int main (int argc, const char * argv[])

{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

MyClass *myClass = [[MyClass alloc] init];

//普通调用

NSString *normalInvokeString = [myClass appendMyString:myString];

NSLog(@"The normal invoke string is: %@", normalInvokeString);

//NSInvocation调用

SEL mySelector = @selector(appendMyString:);

//方法签名类,需要被调用消息所属的类MyClass ,被调用的消息appendMyString:

NSMethodSignature * sig = [[myClass class]

instanceMethodSignatureForSelector: mySelector];

//根据方法签名创建一个NSInvocation

NSInvocation * myInvocation = [NSInvocation invocationWithMethodSignature: sig];

//设置调用者也就是MyClass的实例对象,在MyClass里也可以用self替代

[myInvocation setTarget: myClass];

[myInvocation setSelector: mySelector];

//如果此消息有参数需要传入,那么就需要按照如下方法进行参数设置,需要注意的是,atIndex的下标必须从2开始。原因为:0 1 两个参数已经被target 和selector占用

NSString *myString = @"My string";

[myInvocation setArgument: &myString atIndex: 2];

NSString * result = nil;

[myInvocation retainArguments];//retain所有参数,防止参数被释放dealloc

[myInvocation invoke]; //消息调用

[myInvocation getReturnValue: &result]; //获取返回值类型id returnType = sig.methodReturnType;

NSLog(@"The NSInvocation invoke string is: %@", result);

[myClass release];

[pool drain];

return 0;

}

MyClass.h

[html] view
plaincopy

#import <Foundation/Foundation.h>

@interface MyClass : NSObject {

}

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

@end

MyClass.m

[html] view
plaincopy

#import "MyClass.h"

@implementation MyClass

- (id)init

{

self = [super init];

if (self) {

// Initialization code here.

}

return self;

}

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

{

NSString *mString = [NSString stringWithFormat:@"%@ after append method", string];

return mString;

}

- (void)dealloc

{

[super dealloc];

}

@end

这里说明一下[myInvocation setArgument: &myString atIndex: 2];为什么index从2开始

文档中的说明

Indices 0 and 1 indicate the hidden arguments self and _cmd, respectively; you should set these values directly with the setTarget: and setSelector: methods. Use indices 2 and greater for the arguments normally passed in a message.意思就是0和1是隐藏参数,而这两个参数是要在setTarget和setSelector设置的,所以我们调用方法中的参数就要从2开始了,如果有多个参数,那么就依次递增,ok,就写这么多

原文链接:http://blog.csdn.net/volcan1987/article/details/6690208
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐