Skipping painful migration with Core Data and move

2020-06-28 00:58发布

问题:

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:

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