2012-05-14 42 views
2

如何实现以下块?在后台实现一个块,然后在完成后在主线程上运行另一个块?

我需要在后台运行一些任务。 然后在后台任务完成后,一些任务将在主线程中运行。

为什么我使用块是因为我需要更新传入此方法的视图。

- (void)doALongTask:(UIView *)someView { 

    [self doSomethingInBackground:^{ 

     // Runs some method in background, while foreground does some animation. 
     [self doSomeTasksHere]; 

    } completion:^{ 

     // After the task in background is completed, then run more tasks. 
     [self doSomeOtherTasksHere]; 

     [someView blahblah]; 

    }]; 
} 

还是有更简单的方法来实现这个? 谢谢。

+0

你的问题是什么,到底是什么?如何实现'doSomethingInBackground:completion:'以便在主线程上调用完成处理程序?如果有更多/更简单的方法来实施......无论“这个”在你的问题中是什么意思? – danyowdee

回答

10

我不确定您是否在询问块的工作方式或如何在主线程上运行完成处理程序。

根据您的代码,您调用doSomethingInBackground并传入两个块作为参数。这些块必须在doSomethingInBackground方法中调用才能运行。 doSomethingInBackground必须是这个样子:

-(void)doSomethingInBackground:(void (^))block1 completion:(void (^))completion 
{ 
    // do whatever you want here 

    // when you are ready, invoke the block1 code like this 
    block1(); 

    // when this method is done call the completion handler like this 
    completion(); 
} 

现在如果你想确保你的完成处理程序在主线程上运行,你会改变你的代码看起来像这样:

- (void)doALongTask:(UIView *)someView { 

    [self doSomethingInBackground:^{ 

     // Runs some method in background, while foreground does some animation. 
     [self doSomeTasksHere]; 

    } completion:^{ 
     // After the task in background is completed, then run more tasks. 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      [self doSomeOtherTasksHere]; 
      [someView blahblah]; 
     }); 
    }]; 
} 

这我的回答基于你写的代码。但是,如果这个评论“我需要在后台运行一些任务,那么在后台任务完成后,一些任务将在主线程中运行”更能反映你实际正在尝试做什么,然后你只是需要这样做:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    // do your background tasks here 
    [self doSomethingInBackground]; 

    // when that method finishes you can run whatever you need to on the main thread 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self doSomethingInMainThread]; 
    }); 
}); 
相关问题