核心数据从父NSManagedObjectContext获取失败

时间:2015-09-28 11:31:22

标签: ios core-data nsmanagedobjectcontext

我正在使用父/子NSManagedObjectContext结构在单独的线程中执行一些核心数据操作。操作及其代码按以下顺序排列:

1)删除核心数据中的所有条目(使用父/子结构)

NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObjectContext *bgContext = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType];
bgContext.parentContext = context;

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:context];
[fetchRequest setEntity:entity];

[bgContext performBlockAndWait:^{

    NSError *error;
    NSArray *items = [bgContext executeFetchRequest:fetchRequest error:&error];

    for (NSManagedObject *managedObject in items) {
        [bgContext deleteObject:managedObject];
        [bgContext save:nil];
    }

    NSLog(@"%@ object deleted",entityDescription);

}];

[context performBlockAndWait:^{
    [context save:nil];
}];

2)向核心数据插入新条目(使用父/子结构)

 NSManagedObjectContext *context = [self managedObjectContext];
    NSManagedObjectContext *bgContext = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    bgContext.parentContext = context;

    [bgContext performBlockAndWait:^{
        for (int i = 0; i<quantityCol.count; i++)
        {
            NSManagedObject *Sales = [NSEntityDescription insertNewObjectForEntityForName:@"Transactions" inManagedObjectContext:bgContext];

            NSString *product = [productTitleCol objectAtIndex:i];
            NSString *city = [cityTitleCol objectAtIndex:i];
            NSString *customer = [customerTitleCol objectAtIndex:i];

            [Sales setValue:product forKey:@"product"];
            [Sales setValue:city forKey:@"city"];
            [Sales setValue:customer forKey:@"customer"];

            NSError *err;
            [bgContext save:&err];
            if (err) {
                NSLog(@"%@",err);
            }
            [self.managedObjectContext performBlock:^{
                [self.managedObjectContext  save:nil];
            }];
        }
    }];

3)获取项目(在主线程上使用NSManagedObjectContext)

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Transactions"];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Transactions" inManagedObjectContext:self.managedObjectContext];

fetchRequest.resultType = NSDictionaryResultType;
fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"Date"]];
fetchRequest.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"Date" ascending:NO]];
fetchRequest.returnsDistinctResults = YES;
distinctDate = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];

一切的顺序如上。现在一切似乎工作正常,主线程在任何时候都没有被阻止直到第三步。当我尝试从核心数据中获取项目时,我什么都没得到。请注意,这是我第一次使用子/父结构,所以我不确定我是否完全正确。

0 个答案:

没有答案