0

我想运行一个需要很长时间的块,比如 1 分钟。我想要一个 HUD 向用户显示处理正在进行中。用户在处理过程中不要使用界面。以下代码是我失败的尝试。HUD 未出现,处理未完成/运行。我看到以下代码块完成,然后 CoreData 工作,NSFetchedResultsController,NSNotification 东西响应主 MOC 中的更改。基本上,我希望主线程只运行块和 HUD。

dispatch_sync(dispatch_get_main_queue(), ^{
  [ProgressHUD show:@"Migrating data..."];
  // version update run, move any new data from new sourceDB to user's current DB
  [self loadSourceStore];
  [self deepCopyFromPersistentStore:nil];
  [ProgressHUD dismiss];
});

这会在屏幕上提供一个 HUD 来宣布长期运行,并且 HUD 会停止使用该界面。

我该怎么做?非常感谢阅读,马克

我接受了下面尼古拉的回答。我无法在那里格式化我的解决方案,所以我在这里提供这对我有用:

dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
 MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:appDel.rootTableViewController.tableView animated:YES]; 
 hud.labelText = @"Migrating data..."; 
 dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC);        
 dispatch_after(popTime, concurrentQueue, ^(void){ 
    // long run code here //
    [MBProgressHUD hideHUDForView:appDel.rootTableViewController.tableView animated:YES]; 
});
4

1 回答 1

1

你在调用之后阻塞了主线程+[ProgressHUD show:],所以HUD没有机会显示。在显示 HUD 之后等待一次运行循环迭代,然后再开始长时间运行的任务(使用嵌套dispatch_async调用)或在后台执行此任务(NSManagedObjectContext例如,使用私有队列)。

于 2014-07-28T10:24:50.067 回答