在Objective-C中通过NSInvocation将参数传递给NSInvocationOperation

时间:2014-05-23 19:06:52

标签: objective-c

我正在更多地熟悉NSOperation并发性,我遇到了NSInvocationOperation的问题。

以下是我想要运行的方法:

- (void) myTaskMethod:(NSString *)stringArg {
    NSLog(@"StringArg: %@", stringArg);
}

以下是我如何调用它 **工作**

NSInvocationOperation * invocationOperation2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(myTaskMethod:) object:@"HELLO WORLD!"];
invocationOperation2.completionBlock = ^{
    NSLog(@"We Finished w/ NSInvocationOperation");
};
[invocationOperation2 start];

问题

我尝试通过准备NSInvocation并以这种方式传递它来以不同的方式执行此操作。这是我的代码:

NSMethodSignature *sig = [self methodSignatureForSelector:@selector(myTaskMethod:)];
NSInvocation * myTaskMethodInvocation = [NSInvocation invocationWithMethodSignature:sig];
NSString * hello = @"Hello From NSInvocation";
[myTaskMethodInvocation setArgument:&hello atIndex:2];
NSInvocationOperation * invocationOperation1 = [[NSInvocationOperation alloc]initWithInvocation:myTaskMethodInvocation];
invocationOperation1.completionBlock = ^{
    NSLog(@"We finished w/ NSInvocation");
};
[invocationOperation1 start];

正在记录"我们完成了w / NSInvocation"但是,myTaskMethod:永远不会运行。我想我错过了一些东西,所以任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

来自invocationWithMethodSignature的文档:

  

新对象必须将其选择器设置为setSelector:及其   在调用之前,参数设置为setArgument:atIndex:

我认为您需要添加:

[myTaskMethodInvocation setTarget:self];
[myTaskMethodInvocation setSelector:@selector(myTaskMethod:)];