Skipping painful migration with Core Data and move

2020-06-28 00:48发布

I'm spending a lot of time massaging core data into a new migration when I don't even care about the old data. Instead of dealing with the hassle of mapping models each time I change my data model, is there a way to just delete all existing data and jump to the new data model?

1条回答
姐就是有狂的资本
2楼-- · 2020-06-28 01:39

Yep, just delete the store file and recreate it. I often (at least in development) have my code try an auto migration, and if that fails, blow away the store and start over:

// storefile is an NSURL to the store file, mom is the NSManagedObjectModel
NSError *err = nil;
NSPersistentStoreCoordinator *psc = [[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom] autorelease];
[psc addPersistentStoreWithType:NSSQLiteStoreType
                  configuration:nil
                            URL:storefile
                        options:[NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES],
                                 NSMigratePersistentStoresAutomaticallyOption,
                                 [NSNumber numberWithBool:YES],
                                 NSInferMappingModelAutomaticallyOption,
                                 nil]
                          error:&err];
if (err) // could be more specific about testing this error
{ // assume automigration failed, blow away the store and try again
  err = nil; // log it first!
  [[NSFileManager defaultManager] removeItemAtURL:storefile
                                            error:nil];
  [psc addPersistentStoreWithType:NSSQLiteStoreType
                    configuration:nil
                              URL:storefile
                          options:nil
                            error:&err];
}
// then test err again and give up if there's still a problem
查看更多
登录 后发表回答