2012-08-28 41 views
0

-[NSInvocationOperation initWithTarget:selector:object:]只接受一個要作爲將被調用的方法的參數傳遞的對象。我想用兩個參數;我怎樣才能做到這一點?爲NSInvocationOperation設置多個參數

這是我的代碼:

- (void)loadImage:(NSURL *)imageURL 
{ 
    NSOperationQueue *queue = [NSOperationQueue new]; 
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
             initWithTarget:self 
             selector:@selector(requestRemoteImage:) 
             object:imageURL]; 
    [queue addOperation:operation]; 
} 

- (void)requestRemoteImage:(NSURL *)imageURL 
{ 
    NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageURL]; 
    UIImage *image = [[UIImage alloc] initWithData:imageData]; 

    [self performSelectorOnMainThread:@selector(placeImageInUI:) withObject:image waitUntilDone:YES]; 
} 
+1

@ H2CO3的答案是完全正確的,但我強烈建議不要使用'NSInvocationOperation',除非你對它有強烈的需求。 'NSBlockOperation'生成速度更快,編碼更容易,而且更靈活。調用創建起來非常昂貴,並且已經被塊廣泛地取代。 –

回答

-1

您可以發送字典,所有你想要

+1

開發你的答案一點,尤其是當一個新用戶可能不像你試驗的那樣 – Geoffroy

+0

@Geoffroy你是對的。 但我嘗試應用它併成功。 –

+0

@besharkhalid沒問題,我只是審查新的答案:) – Geoffroy

1

您可以使用NSInvocation的對象初始化opertation值:

- (id)initWithInvocation:(NSInvocation *)inv 

(NSInvocation可以處理多個參數);或者你可以將所需的參數包裝到NSArray或NSDictionary中,只要它們是對象。

1

詢問其操作invocation並在將操作添加到隊列之前修改該操作。

NSInvocation * invocation = [operation invocation]; 
[invocation setArgument:&anotherObject atIndex:3];  
// Indexes 0 and 1 are self and cmd, and you've already used index 2 

或者as Rob Napier suggested,使用NSBlockOperation,這是更爲靈活和易於使用。

+0

我想在requestRemoteImage方法中使用新的參數 –