簡體   English   中英

在Objective-C中通過NSInvocation將參數傳遞給NSInvocationOperation

[英]Passing Argument to NSInvocationOperation via NSInvocation in 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];

它正在記錄“我們完成了NSInvocation”,但是myTaskMethod:從未運行。 我想我缺少了一些東西,因此可以提供任何幫助。

invocationWithMethodSignature的文檔中:

在調用新對象之前,必須先將其選擇器設置為setSelector: setArgument:atIndex:並將其參數設置為setArgument:atIndex:

我認為您需要添加:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM