0

これは私のコードです:

        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") には表示されません。手がかりはありますか??

4

1 に答える 1

1

完了ハンドラーでは、管理対象オブジェクトまたは管理対象オブジェクト コンテキストに送信されるすべてのメソッドが、 または を使用してそれぞれの実行コンテキストで実行されるようにする必要がありますperformBlock:performBlockAndWait:

    NSManagedObjectContext *context = appDelegate.managedObjectContext;
    [context performBlockAndWait:^{
        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]);
        }
    }];

管理対象オブジェクトがメイン スレッドでアクセスされる場合、実行コンテキストがメイン スレッドと等しいことが必須です。

詳細については、Apple Docs: NSManagedObjectContext Reference、特に「同時実行性」の章を参照してください。

于 2014-01-08T14:34:08.620 に答える