Search code examples
databaseswiftcore-datacore-data-migration

CoreData Migration new attribute Swift


I have a CoreData database in Swift. I added a new version in which i added 3 more attributes. The problem is that if a user has already added some values to the database, before I added the new attributes to the database, the app will crash. This is due I want to read out the whole database with all its values. But if the user has added some values before I added the new version, then there will be no values in the new added attributes. So I read out the attributes which hold no values. Can I change it so like all old attributes will automatically be something like an empty string, so it won't crash? Or can I catch the error or something?


Solution

  • One way is to write a reader function that throws and in the error handling call a different function which is for the old inputs . PS, would be easier to help you if you post the code

    //error type
    enum Error: ErrorType{
        case OldInput
    }
    func fetchFromDatabase() throws {
       //do you fetching 
       if //condition if the new attribute exists {
            //fetch
            return
       }
       throw Error.OldInput
    }
    
    //calling it
    do {
       try fetchFromDatabase()
    } catch (error) {
       fetchFromDatabaseOld()
    }