此NSPersistentStoreCoordinator无法执行保存操作

时间:2016-07-19 07:54:08

标签: ios objective-c local-storage nsmanagedobjectcontext nspersistentstore

当我登录应用程序时,它似乎在NSManagedObjectContext * managedObjectContext = self.managedObjectContext崩溃;在下面的保存上下文方法中,并给出错误“此NSPersistentStoreCoordinator没有持久存储(模式不匹配或迁移失败)。它无法执行保存操作。”,

- (BOOL) saveContext
{
    @synchronized (_localStorage) {
        //NSLog(@"----------------------------Save context called---------------------------");
        BOOL result = TRUE;
        NSError *error = nil;
        NSManagedObjectContext *managedObjectContext = self.managedObjectContext;

        if (managedObjectContext != nil)
        {
            if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
            {
                NSLog(@"----------------------------Save context failed---------------------------");
                result = FALSE;
                NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            }
        }

        //NSLog(@"----------------------------Save context completed---------------------------");

        return result;
    }
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
    {
        if (__persistentStoreCoordinator != nil)
        {
            return __persistentStoreCoordinator;
        }

        NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Badger.sqlite"];

        NSError *error = nil;
        __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

        NSDictionary *options = @{
                                  NSMigratePersistentStoresAutomaticallyOption : @YES,
                                  NSInferMappingModelAutomaticallyOption : @YES,
                                  NSSQLitePragmasOption : @{@"journal_mode" : @"DELETE"}
                                  };

        if(![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
        {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        }

        return __persistentStoreCoordinator;
    }

1 个答案:

答案 0 :(得分:0)

每当我们修改Core Data应用程序的数据模型时,持久性存储就会与数据模型不兼容并导致崩溃。要解决这个问题,我们必须进行数据迁移。 有关Core Data迁移的教程,请按照以下文章进行操作。 http://code.tutsplus.com/tutorials/core-data-from-scratch-migrations--cms-21844