最近NSInvocationの使い方を聞かれたので、NSInvocationの小さな例を書きました


ダイレクトコード
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は非表示のパラメータですが、この2つのパラメータはsetTargetとsetSelectorで設定されているので、呼び出し方法のパラメータは2から始まります.複数のパラメータがあれば、順番に増やして、ok、こんなに書きます.