2

I need to add a new property to a class modeled in SwiftData after the project has been compiled and some data already been saved to the underlying container. But the app crashed when I tried to build and run the project with the modified data model. For example, the data model is as follows:

import Foundation
import SwiftData

@Model
final class TileView {
    @Attribute (.unique) var tileName
    var tileLegth: Double
    var tileWidth: Double
    var tilePatternName: String
    // var tileType: String // This is later added

   init(tileName: String, tileLength: Double, tileWidth: Double, tilePatternName: Double/*, tileType: String*/) {
       self.tileName = tileName
       self.tileLength = tileLength
       self.tilePatternName = tilePatternName
       // self.tileType = tileType
   }
}

When the commented code in the above code snippet is uncommented after the app has been built and run initially, the app crashes if it is built and run subsequently. Is there a safe way to modify (e.g. add to or remove properties) existing models like the above? Thank you so much.

2
  • 2
    Look into "migration" and SchemaMigrationPlan. Commented Nov 11, 2023 at 5:17
  • 3
    Or you can give a default value for the new property and SwiftData will do the migration for you. Commented Nov 11, 2023 at 7:10

1 Answer 1

-4

Problem solved. It's because I didn't migrate the @Relationship var, so the runtime couldn't find it in the new version of the model. Sorry, I didn't put the @Relationship var in the code snippet I provided in my post because I didn't know it was the missing of the @Relationship var in the initialiser of the new version that had caused the problem.

Thank you for your participation and suggestions.

Sign up to request clarification or add additional context in comments.

4 Comments

This would be more helpful if you showed the code both before and after the needed change(s).
Thank you, @HangarRash for your kind suggestion. But that would a whole lot of code to paste here. I'm sorry I'm in a hurry to do something else at the moment. I may come up with the code whenever I've got a minute later.
I certainly don’t mean all of your code. Just the relevant changes to your class.
Or maybe it's better you remove the whole question then since it seems to be based on a mistake and isn't that helpful to others.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.