Friday, September 27, 2024

NSManagedObjectID and PersistentIdentifier

Fatbobman:

However, in SwiftData, there is currently no similar property or method to directly determine the [temporary] state of a PersistentIdentifier. Since SwiftData’s mainContext defaults to the autoSave feature (developers do not need to explicitly save data), identifiers may temporarily be unusable in other contexts after creating data objects.

[…]

SwiftData’s default implementation is still based on Core Data, so the format of PersistentIdentifier is very similar to that of NSManagedObjectID[…]

You can see this when printing it, but crucially there is still no API to convert between the two types.

Starting with Xcode 16, the Core Data framework has officially annotated [NSManagedObjectID as Sendable], so developers no longer need to do it manually.

It’s interesting that it took so long since NSManagedObjectID has always been threadsafe outside of Swift Concurrency.

Although an NSManagedObjectID instance contains sufficient information to indicate the data post-persistence, it cannot retrieve the corresponding data when used with another NSPersistentStoreCoordinator instance, even if the same database file is used. In other words, an NSManagedObjectID instance cannot be used across coordinators.

This is because the NSManagedObjectID instance also includes private properties of the corresponding NSPersistentStore instance.

I kind of look at it backwards from this. The NSManagedObjectID doesn’t contain very much information—it’s often squeezed into a tagged pointer. How is this possible when it logically contains a reference to the entity description and the persistent store, in addition to the primary key? I assume that it’s storing abbreviations for these, which can only be interpreted with respect to a coordinator.

Previously:

Comments RSS · Twitter · Mastodon

Leave a Comment