Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]; }];
};
like image 834
Jeremy Mullin Avatar asked May 24 '11 15:05

Jeremy Mullin


People also ask

What is a completion block?

The block to execute after the operation's main task is completed.

What are operation queues?

An operation queue invokes its queued Operation objects based on their priority and readiness. After you add an operation to a queue, it remains in the queue until the operation finishes its task. You can't directly remove an operation from a queue after you add it. Note.

What is block operation in Swift?

Overview. The BlockOperation class is a concrete subclass of Operation that manages the concurrent execution of one or more blocks. You can use this object to execute several blocks at once without having to create separate operation objects for each.


1 Answers

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.

like image 176
gcamp Avatar answered Nov 02 '22 23:11

gcamp