9

我已经为此苦苦挣扎了一段时间,Apple 的文档和 SO 到目前为止并没有帮助。我在 UIManagedDocument 上使用了 ManagedObjectContext,下面的代码运行良好。然后我决定在 AppDelegate 中使用 Apple 的 CoreData 模板,因此在 AppDelegate 中创建模型、持久存储协调器和上下文。使用 AppDelegate 的上下文获取没有问题,但后台保存是个问题。我应该在我正在保存的线程上拥有本地上下文,并且按照 Apple 的要求拥有相同的持久性存储协调器。但是下面的代码实际上并没有保存数据。这里有人可以建议吗?谢谢你。

- (void)fetchAndPersist
{
    dispatch_queue_t ffetchQ = dispatch_queue_create("ForFetch", NULL);
    dispatch_async(ffetchQ, ^{

        NSManagedObjectContext *secureManagedObjectContext;
        NSPersistentStoreCoordinator *coordinator = [appDelegate persistentStoreCoordinator];
        if (coordinator != nil) {
            secureManagedObjectContext = [[NSManagedObjectContext alloc] init];
            [secureManagedObjectContext setPersistentStoreCoordinator:coordinator];
        }

        // find missing date
        DataManager *dataManager = [[DataManager alloc] init];
        NSDate *missingDate = [dataManager findMissingDateFromDate:selectedDate inContext:secureManagedObjectContext];

        if (missingDate) {
            // fetch and parse data
            DataFetcher *dataFetcher = [[dataFetcher alloc] init];
            NSDictionary *fetchResponse = [dataFetcher parseDataForDate:missingDate];

            // persist it in a block and wait for it
            [secureManagedObjectContext performBlock:^{
                DataStore *dataStore = [[DataStore alloc] init];
                BOOL parsingError = [dataStore persistData:fetchResponse inContext:secureManagedObjectContext];

                if (parsingError) {
                    // handle error
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // perform on main
                        [self fetchAndPersist];
                    });
                }
            }];
        }
    });
}
4

2 回答 2

18

尝试使用父/子上下文:

http://www.cocoanetics.com/2012/07/multi-context-coredata/

在上面的链接中,您可以找到代码示例。

于 2013-09-15T13:35:41.327 回答
3

发生崩溃是因为您NSManagedObjectContext使用的是旧的、过时的线程限制模型来实现 Core Data 并发

secureManagedObjectContext = [[NSManagedObjectContext alloc] init];

init只是initWithConcurrencyType:参数的包装NSConfinementConcurrencyType。这使用线程限制模型创建上下文,该模型不能使用performBlock:or performBlockAndWait:。只有使用较新(不是过时!)队列限制模型的上下文才能使用这些方法,并且必须使用这些方法来访问上下文或属于它的对象。要使用队列限制和私有队列创建上下文:

secureManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];

如果您的代码被迁移到使用私有队列上下文,您还可以删除您的串行调度队列,因为私有队列上下文提供了等效的功能。

于 2014-09-14T02:05:13.790 回答