对于网络代码,我将在NSULRConnection上使用异步方法,并处理返回到后台队列的数据。只有修改UI并且需要在主队列中的数据才会被调度(使用GCD)到主队列中。
NSOperationQueue *yourQueue = [[NSOperationQueue alloc] init];
[NSULRConnection sendAsynchronousRequest:yourRequest
queue:yourQueue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
// The code inside here gets processed once the url request completes ...
// It happens in the background on "yourQueue".
[self doSomeExpensiveDataProcessingWithData:data];
dispatch_sync(dispatch_get_main_queue(), ^{
// Update UI on the main thread and wait to continue processing the data
[self updateUI];
});
[self doSomeMoreDataProcessing];
dispatch_sync(dispatch_get_main_queue(), ^{
// Update UI on the main thread and wait to continue processing the data
[self finalUpdateOfUI];
});
}];
网络代码我一般像异步回调作为设计图案的例子之外。很容易独立地测试不同的回调函数,并将不同的回调函数(如错误处理和数据处理)分成不同的方法,从而在这些方法中提供更加集中的代码。
GCD非常适合快速在另一个线程上执行几行代码或异步调度某些工作。
NSThread很少再使用。
对我来说,这听起来像你没有正确使用GCD。你应该发布代码。 – vikingosegundo 2012-07-20 08:18:55
NSURLConnection有一个sendAsynchronousRequest:queue:completionHandler:方法。你可以使用它。 – Francesco 2012-07-20 08:27:03