How to add more attributes to existing core data entity?

前端 未结 3 825
轮回少年
轮回少年 2021-02-02 12:16

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 t

3条回答
  •  离开以前
    2021-02-02 12:42

    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(".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.

提交回复
热议问题