Search code examples
grand-central-dispatchhud

How to run only a HUD and a synchronous block of code on main thread using CoreData?


I want to run a block that take a long time say, 1 minute. I want a HUD to show the user that processing is being done. The user is not to use the interface during the processing. The following code is my failed attempt. The HUD does not appear and the processing does not finish/run. I see the following code block finishing and then CoreData work, NSFetchedResultsController, NSNotification stuff responding to the changes in the main MOC. Basically, I want the main thread running nothing but the block and the 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];
});

This provides a HUD on screen announcing the long run, and the HUD stops use of the interface.

How should I do this? Many thanks for reading, Mark

I accepted the answer from Nikolay below. I could not format my solution there so I provide it here This worked for me :

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]; 
});

Solution

  • You're blocking the main thread after calling +[ProgressHUD show:], so HUD has no chance to be displayed. Either wait one run loop iteration after showing the HUD & before starting your long running task (using nested dispatch_async call) or perform this task in background (using NSManagedObjectContext with private queue, for example).