这是操作队列完成块的正确用法吗?

发布于 2024-11-09 14:24:52 字数 1244 浏览 0 评论 0原文

我第一次使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

原谅过去的我 2024-11-16 14:24:52

就是这样。如果您想使用操作队列而不是 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文