【发布时间】:2011-09-01 01:55:41
【问题描述】:
我是第一次使用 Objective-C 块和操作队列。我正在加载一些远程数据,而主 UI 显示一个微调器。我正在使用完成块来告诉表重新加载其数据。与documentation mentions 一样,完成块不在主线程上运行,因此表格会重新加载数据但不会重新绘制视图,直到您在主线程上执行某些操作(例如拖动表格)。
我现在使用的解决方案是调度队列,这是从完成块刷新 UI 的“最佳”方式吗?
// define our block that will execute when the task is finished
void (^jobFinished)(void) = ^{
// We need the view to be reloaded by the main thread
dispatch_async(dispatch_get_main_queue(),^{
[self.tableView reloadData];
});
};
// create the async job
NSBlockOperation *job = [NSBlockOperation blockOperationWithBlock:getTasks];
[job setCompletionBlock:jobFinished];
// put it in the queue for execution
[_jobQueue addOperation:job];
更新 根据@gcamp 的建议,完成块现在使用主操作队列而不是 GCD:
// define our block that will execute when the task is finished
void (^jobFinished)(void) = ^{
// We need the view to be reloaded by the main thread
[[NSOperationQueue mainQueue] addOperationWithBlock:^{ [self.tableView reloadData]; }];
};
【问题讨论】:
标签: cocoa-touch ios nsoperationqueue grand-central-dispatch