2011-05-24 64 views
12

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

回答

17

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

+0

很酷,我不知道mainQueue。一点清洁剂和更一致的方式。谢谢! – 2011-05-24 16:13:20

+0

使用[NSOperationQueue mainQueue]和dispatch_get_main_queue()之间是否存在实际差异? – 2011-06-08 00:03:09

+1

就结果而言,没有。但它在使用方式上有所不同。 'NSOperationQueue'使用(显然)'NSOperation'和GCD(dispatch_get_main_queue)使用块。 – gcamp 2011-06-08 01:54:55