这是操作队列完成块的正确用法吗?
我第一次使用 Objective-C 块和操作队列。我正在加载一些远程数据,同时主 UI 显示一个微调器。我正在使用完成块来告诉表重新加载其数据。作为 文档提到,完成块不会在主线程上运行,因此表会重新加载数据,但不会重新绘制视图,直到您在主线程上执行某些操作线程就像拖桌子一样。
我现在使用的解决方案是调度队列,这是从完成块刷新 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]; }];
};
I'm using Objective-C blocks and Operation Queues for the first time. I'm loading some remote data while the main UI shows a spinner. I'm using a completion block to tell the table to reload its data. As the documentation mentions, the completion block does not run on the main thread, so the table reloads the data but doesn't repaint the view until you do something on the main thread like drag the table.
The solution I'm using now is a dispatch queue, is this the "best" way to refresh the UI from a completion block?
// 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];
Update
Per @gcamp's suggestion, the completion block now uses the main operation queue instead of 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]; }];
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就是这样。如果您想使用操作队列而不是 GCD 作为完成块,您也可以使用
[NSOperationQueue mainQueue]
。That's exactly it. You can also use
[NSOperationQueue mainQueue]
if you want to use an operation queue instead of GCD for your completion block.