Core Data: Add a column on a table
Asked Answered
A

0

0

I just want to add a column on a table for my new version of my app, and keep the filled columns. So I work with Core Data, this is my momd:

enter image description here

On my appDelegate:

/* CORE DATA */

// MARK: - Core Data stack

lazy var applicationDocumentsDirectory: NSURL = {
    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    return urls[urls.count-1]
}()

lazy var managedObjectModel: NSManagedObjectModel = {
    let modelURL = NSBundle.mainBundle().URLForResource("solutis", withExtension: "momd")!
    return NSManagedObjectModel(contentsOfURL: modelURL)!
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("solutis.sqlite")
    var failureReason = "There was an error creating or loading the application's saved data."
    do {
        try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
    } catch let error as NSError {
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason
        dict[NSUnderlyingErrorKey] = error
        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
        abort()
    } catch {
        fatalError()
    }

    return coordinator
}()


lazy var managedObjectContext: NSManagedObjectContext = {
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

// MARK: - Core Data Saving support

func saveContext () {
    if managedObjectContext.hasChanges {
        do {
            try managedObjectContext.save()
        } catch {
            let nserror = error as NSError
            NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
            abort()
        }
    }
}

So if the user update the app with a filled table, he gonna keep the data and have the new version of the table.

But how to do ? I juste learned to add Model version, but how to retrieve old data ?

Accede answered 7/9, 2016 at 13:8 Comment(3)
Apple provides a "Core Data Model Versioning and Data Migration Programming Guide" which should cover all that stuff. You should also find some tutorials about "Core Data migration".Various
@MartinR But if I rename the attributes ?Accede
Reading the Core Data Guide is good advice (see @MartinR). If you read it you will remember the option NSMigratePersistentStoresAutomaticallyOption with NSPersistentStore. It is necessarily required to switch it on. Renaming of columns is good for Lightweight Migration. No trouble to be expected. Adding a new column could be more challenging (e.g. if constraints does not allow empty values and no default value is given). Bear in mind: under the hood only ALTER TABLE statements and others will be performed, no magic ...Bromism

© 2022 - 2024 — McMap. All rights reserved.