Skip to content

Instantly share code, notes, and snippets.

@Monntay
Created October 21, 2019 08:20
Show Gist options
  • Select an option

  • Save Monntay/612f1e848432cff55f64f791b416ffaa to your computer and use it in GitHub Desktop.

Select an option

Save Monntay/612f1e848432cff55f64f791b416ffaa to your computer and use it in GitHub Desktop.
class MigrationPolicy: NSEntityMigrationPolicy {
override func createDestinationInstances(forSource sInstance: NSManagedObject, in mapping: NSEntityMapping, manager: NSMigrationManager) throws {
// MARK: 1 - Check if it is a person
if sInstance.entity.name == "Person" {
// MARK: 2 - fetch the values
let firstName = sInstance.primitiveValue(forKey: "firstname") as? String
let lastName = sInstance.primitiveValue(forKey: "lastname") as? String
let age = sInstance.primitiveValue(forKey: "age") as? String
let isTeacher = sInstance.primitiveValue(forKey: "teacher") as? Bool
// MARK: 3 - Create teacher or person
let person = isTeacher == true ? NSEntityDescription.insertNewObject(forEntityName: "Teacher", into: manager.destinationContext) : NSEntityDescription.insertNewObject(forEntityName: "Student", into: manager.destinationContext)
person.setValue(firstName, forKey: "firstName")
person.setValue(lastName, forKey: "lastName")
person.setValue(age, forKey: "age")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment