Can I use NSPersistentCloudKitContainer while at the same time adding extra fields to my CloudKit CKRecord?

For example, because NSPersistentCloudKitContainer doesn't support ordered relationship, I'd like to have an array of references on my CKRecord because CloudKit support NSArray field type; I can then sync these array manually (e.g. persist without relying on Core Data). Is it okay or recommended to do so?

hi,

my guess is that you're playing with fire if you go behind NSPersistentCloudKitContainer's back (!)

if you want to keep the notion of an ordered set for a relationship among two entities that is A <---->> B (many B entities associated with an A, but only one A entity is associated with a given B), then two options come to mind (and these can be handled directly on the Core Data side).

first, add an integer attribute to B to indicate its relative position among all its sibling B objects. if A changes the order of the B objects, just rewrite the position of each (or as may as needed) associated B.

second ... perhaps if each B object represents "lots of data" and you think it an expensive operation to rewrite many B objects when reordered ... then consider adding an intermediate entity C with one integer attribute (perhaps named position) and two relationships: one from C to A (many-to-one) and one from C to B (one-to-one), so that you have A <---->> C <----> B. in essence, each C object represents a single B object, but contains B's order for its associated A object.

if you have an A object in hand, you then know the ordering of the associated B objects with

let associatedCobjects = (A.c as? Set<C>) ?? []  // of type Set<C>
let orderedBObjects = associatedCobjects.ordered(by: { $0.position }).map({ $0.b }) // of type [B] in the proper order

rewriting the position attribute of C objects based on any intended re-ordering of the B object is fairly cheap (no B objects are being updated).

finally, if your original relationship between A and B was many-to-many, i.e., A <<---->> B, this second technique continues to work. that is, you'll now have A <---->> C <<----> B. each C now represents an association of a single A with a single B, while indicating the relative position of B within some associated A object. (i'm not a real database guy, but i believe this is called a join).

hope that helps,

DMG

Can I use NSPersistentCloudKitContainer while at the same time adding extra fields to my CloudKit CKRecord?
 
 
Q