最近有人问NSInvocation怎么用,于是写了个NSInvocation的小例子

时间:2022-05-01 18:56:53

直接上代码

main.h

#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 *myString = @"My string";

//普通调用
NSString *normalInvokeString = [myClass appendMyString:myString];
NSLog(@"The normal invoke string is: %@", normalInvokeString);

//NSInvocation调用
SEL mySelector = @selector(appendMyString:);
NSMethodSignature * sig = [[myClass class]
instanceMethodSignatureForSelector: mySelector];

NSInvocation * myInvocation = [NSInvocation invocationWithMethodSignature: sig];
[myInvocation setTarget: myClass];
[myInvocation setSelector: mySelector];

[myInvocation setArgument: &myString atIndex: 2];

NSString * result = nil;
[myInvocation retainArguments];
[myInvocation invoke];
[myInvocation getReturnValue: &result];
NSLog(@"The NSInvocation invoke string is: %@", result);

[myClass release];

[pool drain];
return 0;
}

MyClass.h

#import <Foundation/Foundation.h>


@interface MyClass : NSObject {

}

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

@end

MyClass.m

#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,就写这么多