2012-06-06 33 views
2

我有一個方法可以構建一個包,將它發送到一個Web服務,取回一個包,打開它並返回一個nsdictionary。如何在後臺隊列中調用它以在請求數據時顯示HUD?在後臺線程上解析來自WebService的JSON數據

+0

你有沒有看着ASIHTTPRequest或AFNetworking?他們使這個過程非常簡單。 – mkral

回答

2

你可以卸下一個新的線程,就像以下

- (void) fetchData 
{ 
    //Show Hud 

    //Start thread 
    [NSThread detachNewThreadSelector:@selector(getDataThreaded) 
    toTarget:self 
    withObject:nil]; 
} 

- (void) getDataThreaded 
{  
    //Start Fetching data 

    //Hide hud from main UI thread 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     //Update UI if you have to 
     //Hide Hud 
    }); 
} 
0

大中央調度(GCD)爲做什麼你問的大力支持。在運行使用GCD的背景是什麼很簡單:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_NORMAL, 0) ^{ 
    NSDictionary* data = [self fetchAndParseData]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self dataRetrieved:data]; 
    }); 
}); 

該調用將立即返回(所以你的用戶界面將繼續響應),當數據準備好dataRetrieved將被調用。

現在,根據fetchAndParse數據的工作原理,它可能需要更復雜。如果你使用NSURLConnection或類似的東西,你可能需要創建一個NSRunLoop來處理gcd線程中的數據回調。無論如何NSURLConnection大部分都是異步的(儘管像didReceiveData這樣的回調將通過UI線程進行路由),因此只有在檢索完所有數據後才能使用gcd來解析數據。這取決於你想要的異步程度。

0

除了以前的回覆,爲什麼不使用NSOperationNSOperationQueue類?這些類是GCD下的抽象類,它們使用起來非常簡單。

我喜歡NSOperation類,因爲它允許在我通常開發的應用程序中對代碼進行模塊化。

要設置NSOperation你可以只繼承它像

//.h 
@interface MyOperation : NSOperation 

@end 

//.m 
@implementation MyOperation() 

// override the main method to perform the operation in a different thread... 
- (void)main 
{ 
    // long running operation here... 
} 

現在在主線程可以提供操作隊列類似如下:

MyOperation *op = [[MyOperation alloc] initWithDocument:[self document]]; 
[[self someQueue] addOperation:op]; 

附:您無法在NSOperationmain方法中啓動異步操作。 main完成後,與該操作鏈接的代理將不會被調用。要說出你可以解釋的事實,但這涉及到處理運行循環或併發行爲。

這裏有一些關於如何使用它們的鏈接。

明明class referenceNSOperation