swift-data

SwiftData PersistentIdentifier saved to UserDefaults?


I'm updating my app from CoreData to SwiftData and came across an issue. My app has multiple users so in CoreData and I assigned each a myID value set to an UUID so I could use UserDefaults to set the preferred user on app load. When switching over I noticed the PersistentIdentifier value and got excited as I could fetch the matching entity with modelContext.model(for: yourID). I decided to use that instead so I updated my UserDefaults code from UUID to this:

    @Published var selectedUserID: PersistentIdentifier? {
        didSet {
            UserDefaults.standard.set(selectedUserID, forKey: "selectedUserID")
        }
    }

    init() {
        self.selectedUserID = UserDefaults.standard.object(forKey: "selectedUserID") as? PersistentIdentifier ?? nil
    }

This code compiles and, of course the id is currently set to nil. My issue now is when I try to assign a user to it ar my app crashes and I get the following error:

Attempt to set a non-property-list object SwiftData.PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://6FE80FC9-0B4C-491E-8093-DED37A619F1B/EnteredUser/p834), implementation: SwiftData.PersistentIdentifierImplementation) as an NSUserDefaults/CFPreferences value for key selectedUserID

Should I go back to an additional UUID field in my user model and find it that way or is there a way to use the PersistentIdentifier value with my UserDefaults?

Thanks for any tips.


Solution

  • PersistentIdentifier conforms to Codable so you can encode it and store it as Data or rather what we store is the id property of PersistentIdentifier.

    This is what I used in my test project

    Encoding:

    let data = try! JSONEncoder().encode(model.id)
    UserDefaults.standard.setValue(data, forKey: "selectedID")
    

    and for the decoding

    if let data = UserDefaults.standard.data(forKey: "selectedID") {
        self.selected = try! JSONDecoder().decode(TestModel.ID.self, from: data)
    }