2012-02-15 94 views
0

我已經編寫了下面的代碼來從NSInvocationOperation重新加載UITableView。但是,在撥打[tableview reloadData]後,界面長時間不會更新。從NSOperation重新加載UITableView

Apple文檔說在NSOperation中不會調用委託方法。

NSOperationQueue *queue = [NSOperationQueue new]; 

NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
              initWithTarget:self 
              selector:@selector(connectToServer) 
              object:nil]; 

[queue addOperation:operation]; 
[operation release]; 
[queue autorelease]; 

- (void) connectToServer 
{ 
    ... 
    ... 
    [tableview reloadData]; 
} 

回答

2

問題是UI更新必須發生在主線程上,並且reloadData通過NSOperationQueue從後臺線程調用。

您可以使用NSObject方法performSelectorOnMainThread:withObject:waitUntilDone:來確保在主線程上發生此類更新。

- (void) connectToServer 
{ 
    ... 
    ... 
    [tableView performSelectorOnMainThread:@selector(reloadData) 
      withObject:nil 
      waitUntilDone:NO]; 
} 

此外,NSOperationQueue不應該是一個局部變量。它應該是這個類的一個保留屬性,並且只在dealloc中發佈。

+0

我已經嘗試過了,它會在輸出一段時間後在ios5中輸出相同的圖片。你能幫忙嗎? – nameless 2012-02-15 06:45:09