10

I'm confused about how to best save an object that contains an array of other objects in CloudKit.

Say I have a todo list app, which has different collections of items. How would I go about saving/fetching a whole collection of items?

Would I have a Record type of Collection, which would have a String Attribute called "Name", and then a Reference List Attribute called "Items"?

I know that the Record type of Item needs to have a Reference Attribute called "Collection", because of how CloudKit references from a child object to its parent.

I have managed to save a Collection without any instances of Item with the following code

func addCollection(collection: Collection!, completion: (error: NSError!) -> ()) {
    if collection == nil
        return
    }
    let collectionRecord = CKRecord(recordType: "Collection")
    CollectionRecord.setObject(collection.name, forKey: "Name")
    privateDB.saveRecord(collectionRecord) {
        record, error in
        dispatch_async(dispatch_get_main_queue()) {
           completion(error: error)
        }
    }
}

The other option is when saving a Collection, to loop through all instances of Item and also save those individually, their Reference Attribute to Collection making the connection on the CloudKit side, but this seems like way too many network calls.

4

1 回答 1

3

对于Item记录,您需要一个CKReferenceCollection. 然后你就可以设置一个CKReferenceAction了。您无需CKReferenceCollection.

拥有 CKReference 对象列表只是您计划使用时的一个选项,CKReferenceAction.None这意味着两个记录类型之间没有严格的关系

如果您有一个Collection对象,那么您可以Item使用检查 CKReference 是否为Collection.

通常不需要保存多条记录。一旦你创建了一个包含项目的集合,关系就可以保持不变。如果您确实需要更改多条记录,那么您可以尝试使用CKModifyRecordsOperationwhich 支持在一个操作中保存多个项目。

将现有记录类型链接Item到时Collection,您确实需要保存每个Item记录类型,因为它有一个 CKReference 到Collecion. 已Item更改,因此必须保存。

于 2015-01-14T12:13:40.680 回答