最近有人问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是隐藏参数,而这两个参数是要在setTarget和setSelector设置的,所以我们调用方法中的参数就要从2开始了,如果有多个参数,那么就依次递增,ok,就写这么多


评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值