I am replacing some CoreData code within my iOS App to use the new SwiftData framework. In my original code, I was saving a CoreData object URI in UserDefaults for a quick bookmark. This allowed me to easily fetch specific object I needed directly.
e.g.
model.objectID().uriRepresentation().absoluteString
While investigating a SwiftData solution, I came across this objectID
property on SwiftData models, which is of type PersistentIdentifier
, which seems to do what I want. But there doesn’t seem to a straight forward way to bookmark this value. PersistentIdentifier
conforms to the "Codeable", which I could save to UserDeafaults, by converting it to Data
, but when I attempt to do that, the returned value doesn’t include any of the necessary data, just an empty values. This is what is created when encoding the id
or objectID
of the Model object.
"{"implementation":{}}"
How can I accomplish this with the new SwiftData framework?
2
Answers
Looks like in Xcode 15 Beta 5 Codable is working as expected.
Until Apple provides this, here is a temporary solution that seems to work well:
FYI, unlike the Core Data method, I made the result of my uriRepresentation extension an Optional to suit the needs of my App.