簡體   English   中英

這是操作隊列完成塊的正確用法嗎?

[英]Is this the correct usage of an Operation Queue completion block?

我第一次使用 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]; }];
};

就是這樣。 如果您想使用操作隊列而不是 GCD 作為完成塊,也可以使用[NSOperationQueue mainQueue]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM