How to add more attributes to existing core data entity?

25,531

Solution 1

So my problem was I had no idea where this persistent store coordinator code goes. It turns out it is automatically created in your AppDelegate implementation when you check "Use Core Data" when creating the project.

So, from the second link here, all you need to do for a light-weight migration (adding new attributes and such) is the following:

  1. Select your .xcdatamodeld
  2. From the menu, choose Editor -> Add Model Version
  3. Name the new version anything you wish, select previous version in "Based on model"
  4. In File Inspector of the .xcdatamodeld, choose Model Version -> Current -> your new model version
  5. Select your new model version inside the .xcdatamodeld in Project Navigator, and do the changes to your model
  6. If you changed attribute names or types, create a mapping model, new file -> Core Data -> Mapping Model -> pick source and destination model versions
  7. Update the mapping in the new mapping model

Change your AppDelegate persistent store coordinator code as follows.

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
  var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
  let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("<data model name>.sqlite")
  var error: NSError? = nil
  var failureReason = "There was an error creating or loading the application's saved data."
  let options = [
    NSMigratePersistentStoresAutomaticallyOption: true,
    NSInferMappingModelAutomaticallyOption: true]
  if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options, error: &error) == nil {
      coordinator = nil
      // Report any error we got.
      var dict = [String: AnyObject]()
      dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
      dict[NSLocalizedFailureReasonErrorKey] = failureReason
      dict[NSUnderlyingErrorKey] = error
      error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
      // Replace this with code to handle the error appropriately.
      // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
      NSLog("Unresolved error \(error), \(error!.userInfo)")
      abort()
  }

  return coordinator
}()

So you only add migration options to the addPersistentStoreWithType call.

Solution 2

If you are only adding attributes to an entity, you can use the automated lightweight migration in Core Data.

Basically all you have to do is pass an NSDictionary instance with the appropriate options when you're adding the persistent store. Here's a code snippet from the end of an accessor method for _persistentStoreCoordinator:

NSNumber *optionYes = [NSNumber numberWithBool:YES];
NSDictionary *options = [NSDictionary dictionaryWithObjects:@[optionYes] forKeys:@[NSMigratePersistentStoresAutomaticallyOption]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
    NSLog(@"Error opening persistent store: %@, %@", error, [error userInfo]);
    abort();
}
return _persistentStoreCoordinator;

If your migration is too complex for a lightweight migration, you'll see an error. Otherwise the migration should run and your database will be updated to match your new schema.

Note that if you're doing this for real on a device, you should back up your .sqlite file first, in case something goes wrong in migration.

Share:
25,531
Queshi Zakir
Author by

Queshi Zakir

Updated on October 01, 2020

Comments

  • Queshi Zakir
    Queshi Zakir over 3 years

    I have a project that is using core data , i need add more attributes(Columns) to existing entity (Column) , if i manually add attribute to data model app crash and it is due to context save which i used to insert data into table previously

    Plz help .. Thank you