【问题标题】:Is this the correct usage of an Operation Queue completion block?这是操作队列完成块的正确用法吗?
【发布时间】: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


    【解决方案1】:

    就是这样。如果您想使用操作队列而不是 GCD 作为完成块,也可以使用 [NSOperationQueue mainQueue]

    【讨论】:

    • 酷,我不知道 mainQueue。这样更干净,更一致。谢谢!
    • 使用 [NSOperationQueue mainQueue] 和 dispatch_get_main_queue() 有实际区别吗?
    • 就结果而言,没有。但是在你使用它的方式上是不同的。 NSOperationQueue 使用(显然)NSOperation 和 GCD (dispatch_get_main_queue) 使用块。
    • @gcamp 但是 NSOperation/Queue 是用 GCD 实现的,所以不管怎样都是小事,不是吗?
    • @0xSina 最终结果是一样的,是的,但是API不同。这正是我在之前的评论中所说的。
    猜你喜欢
    • 2021-12-17
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多