skip to Main Content

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


  1. Chosen as BEST ANSWER

    Looks like in Xcode 15 Beta 5 Codable is working as expected.


  2. Until Apple provides this, here is a temporary solution that seems to work well:

    extension PersistentIdentifier {
    
        public func uriRepresentation() -> URL? {
            if let encoded = try? JSONEncoder().encode(self),
               let dictionary = try? JSONSerialization.jsonObject(with: encoded) as? [String: Any],
               let implementation = dictionary["implementation"] as? [String: Any],
               let uriRepresentation = implementation["uriRepresentation"] as? String {
                return URL(string: uriRepresentation)
            } else {
                return  nil
            }
        } }
    

    FYI, unlike the Core Data method, I made the result of my uriRepresentation extension an Optional to suit the needs of my App.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search