2012-03-01 18 views
3

我目前正在處理一個應用程序,該應用程序在位置發生更改時正在解析APPdelegate類中的一些JSON數據。IOS在另一個線程中解析JSON數據?

我的問題是:「最合適的方式是怎麼做的?」目前,在解析數據時,應用程序被「凍結」,直到數據加載完畢。

我需要一些建議:)

感謝

回答

10

當然也有幾個方面,包括NSThreadNSOperation和老式libpthread。但我覺得最方便的(特別是對於簡單的後臺任務)libdispatch也叫Grand Central Dispatch

使用調度隊列,您可以快速將耗時的任務委派給單獨的線程(或者更準確地說,執行隊列--GCD決定它是線程還是異步任務)。以下是最簡單的示例:

// create a dispatch queue, first argument is a C string (note no "@"), second is always NULL 
dispatch_queue_t jsonParsingQueue = dispatch_queue_create("jsonParsingQueue", NULL); 

// execute a task on that queue asynchronously 
dispatch_async(jsonParsingQueue, ^{ 
    [self doSomeJSONReadingAndParsing]; 

    // once this is done, if you need to you can call 
    // some code on a main thread (delegates, notifications, UI updates...) 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self.viewController updateWithNewData]; 
    }); 
}); 

// release the dispatch queue 
dispatch_release(jsonParsingQueue); 

上述代碼將讀取單獨執行隊列中的JSON數據,而不會阻塞UI線程。這只是一個簡單的例子,GCD還有很多,所以請查看文檔以獲取更多信息。

+0

好方法做到這一點:)我會更多地看它:) – Roskvist 2012-03-01 08:03:44

0

您將需要使用NSURConnections並異步獲取數據(或第三方庫,如ASIHTTPRequest)來獲取數據。如果你在你的主線程中做了所有事情,你的用戶界面將會凍結,直到它處理下載&解析等。所以,看看iOS Multithreading。最後一點,蘋果公司的Locations Sample code給出了你想要的東西:)