2012-09-22 49 views
1

我有一個UISearchBarUISearchDisplayController。當用戶在searchBar:textDidChange:內寫入文本時,我會調用Web服務來過濾我的TableView。問題在於,直到我從Web服務獲得結果時,GUI才停止響應。我試圖用[self performSelector:@selector(callWebService:) withObject:searchText];來解決它,但它仍然沒有響應。如何在不使GUI無響應的情況下進行Web服務調用

編輯:按照Flink的建議,我將performSelector更改爲performSelectorInBackground,但現在tableView沒有正確過濾,它只顯示'沒有結果'。 甚至tableView:numberOfRowsInSection:不會被調用。

再次編輯:我得到'沒有結果'的原因是由於沒有在正確的tableView上調用reloadDataUISearchDisplayController有一個名爲searchResultsTableView的屬性。所以最後我用的是[self.searchDisplayController.searchResultsTableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:false];現在它工作正常。

應該指出,雖然我選擇了performSelectorInBackground,但我可能應該試着在NSURLConnection上使用sendAsynchronousRequest方法 - 請參閱AliSoftware的答案。

回答

1

您需要使您的網絡電話異步。

http://www.raywenderlich.com/4295/multithreading-and-grand-central-dispatch-on-ios-for-beginners-tutorial

在你的情況,你可以改變performSelectorperformSelectorInBackground

+0

謝謝你的回覆。我已經將它改爲'performSelectorInBackground',但是現在tableview顯示'No Results' – kernix

+0

我甚至在web服務調用函數'[tableView performSelectorOnMainThread:@selector(reloadData)withObject:nil waitUntilDone:false] '但它仍然沒有顯示任何結果。 – kernix

+0

如果你在這裏提供代碼,會更容易給出更好的答案 – Shmidt

1

應避免創建一個後臺隊列或線程來執行你的網絡的要求(這是什麼performSelectorInBackground:做),因爲這將創建一個工作線程只是爲了這不如在NSRunLoop上安排請求那樣有效。

致力一個線程將使處理器定期激活線程來檢查是否有一些數據,並創建一個線程是相當矯枉過正。在運行循環中調度請求(作爲運行循環源)將使用網絡中斷來發送來自套接字的輸入數據,因此只有在有實際數據可用時纔會被激活。

爲此,只需要使用由NSURLConnection提供的異步方法。

  • 一種解決方案是使用由NSURLConnection(這是老辦法做到這一點,那是NSURLConnection API早在IOS3中可用的唯一途徑)
  • 另一種更現代的解決方案是提供的委託方法使用易於使用和編碼的NSURLConnection提供的塊API。

    [NSURLConnection sendAsynchronousRequest:request 
                queue:[NSOperationQueue mainQueue] 
             completionHandler:^(NSURLResponse* response, NSData* receivedData, NSError* error) 
    { 
        // Your code to execute when the network request has completed 
        // and returned a response (or timed out or encountered an error) 
        // This code will execute asynchronously only once the whole data is available 
        // (the rest of the code in the main thread won't be blocked waiting for it) 
    }]; 
    // After this line of code, the request is executed in the background (scheduled on the run loop) 
    // and the rest of the code will continue: the main thread will not be frozen during the request. 
    

更多的URL Loading System Programming Guide,並在NSURLConnection class reference

+0

是的,這正是塊的用途! – AliSoftware

相關問題