Do I need to add my own unique id?

Hi,

if I have a @Model class there's always an id: PersistentIdentifier.ID underneath which, according to the current documentation "The value that uniquely identifies the associated model within the containing store.".

So I am wondering if it is (good) enough to rely on this attribute to uniquely identify @Model class entities, or if there are edge cases where it does not work (like maybe when using CloudKit)? If anybody saw some information regarding this, please let me know :-)

Cheers, Michael

Apple: "The best place to ask us coding questions is the Developer Forums."

Also Apple:

I suspect that the persistent identifier is a wrapper for the underlying Core Data objectID: NSManagedObjectID. The caveat with using the core data NSManagedObjectID is that it is unique, and permanent, EXCEPT when the object is first created and before it is persisted. There is an initial temporary objectID assigned that is later replaced with the permanent id.

If you want to use the SwiftData PersistentIdentifier, I would recommend checking that this behavior does or does not transfer over from Core Data.

Personally, I've been burned enough by the complexity of dealing with that Core Data NSManagedObjectID that I just create an id: UUID on my objects rather than rely on the persistence layer id.

I think you probably should use your own ID. I tried to rely on it, but I've watched it with the debugger (probably not in the latest beta) and as rkhamilton said it changes value early in the lifecycle. Unless it's documented somewhere as safe for this purpose, I wouldn't trust it (and possibly not even then).

As others have said, it's probably a good idea to have your own unique id (UUID is probably the easiest way). I believe the core data PersistentIdentifier.ID may only be unique to the record on the current install of the current device. If you're doing syncing and want to reference a record on another device, it might not return the same PersistentIdentifier.ID.

This is a good question that I wish apple would discuss more. Yes as people suggest, it is a wrapper for NSManagedObjectID and it will change until its first save, as discussed here https://www.hackingwithswift.com/quick-start/swiftdata/how-to-save-a-swiftdata-object

It's still not clear to me what is best practice, particularly when syncing with a cloud service or database such as postgres. Should I override the swift data id var with my postgres uuid? or have a separate var "cloudID" for it? Has anyone built real apps (not toy demos) with swift data and a server and found any gotchas or advice?

Do I need to add my own unique id?
 
 
Q