应用程序卡在dispatch_async中

时间:2014-01-08 14:07:35

标签: ios multithreading activity-indicator

这是我的代码:

        LoadViewController *loadingViewController = [[LoadViewController alloc] initWithNibName:@"LoadViewController" bundle:nil];
[self.view addSubview:loadingViewController.view];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) , ^{
    [Util deleteAllObjects:@"Unit"];
    for (NSDictionary *eachUnit in serviceData) {
        //insert in DB
        AppDelegate* appDelegate = [AppDelegate sharedAppDelegate];
        NSManagedObjectContext *context = appDelegate.managedObjectContext;
        Unit *unit = [NSEntityDescription insertNewObjectForEntityForName:@"Unit" inManagedObjectContext:context];

        unit.id_unidade = [eachUnit objectForKey:@"id"];
        unit.title = [eachUnit objectForKey:@"title"];
        unit.image = [eachUnit objectForKey:@"image"];
        unit.address = [eachUnit objectForKey:@"address"];
        unit.desc = [eachUnit objectForKey:@"desc"];
        unit.coord = [eachUnit objectForKey:@"coord"];

        NSError *error;

        if (![context save:&error]) {
            NSLog(@"Ops,fail: %@", [error localizedDescription]);
        }
    }
    NSLog(@"before");
    [self fillUnits];
    NSLog(@"after");

    dispatch_async(dispatch_get_main_queue(), ^(void) {
        NSLog(@"reload");
        [self.tableView reloadData];
        [loadingViewController.view removeFromSuperview];
        NSLog(@"after reload");

    });
});

直到NSLog(@“after”)显示,但从未进入NSLog(@“reload”)。 任何线索??

1 个答案:

答案 0 :(得分:1)

在完成处理程序中,您需要确保使用performBlock:或{{1}在其各自的执行上下文上执行发送到托管对象或托管对象上下文的所有方法。 }}:

performBlockAndWait:

如果您的托管对象将在主线程中被访问,那么执行上下文必须等于主线程。

您可以在Apple Docs中阅读更多内容:NSManagedObjectContext Reference,尤其是“并发”一章。