保存和获取CloudKit参考

时间:2018-10-10 14:47:25

标签: swift cloudkit

我无法使用CloudKit引用创建。数据已保存到CloudKit中,但未引用其父级(列表)。不知道我在做什么错,任何帮助将不胜感激!

保存方法

var list: CKRecord?
var item: CKRecord?    

@objc func save() {
    let name = nameTextField.text! as NSString

    //Fetch Private Database
    let privateDatabase = CKContainer.default().privateCloudDatabase

    if item == nil {
        //Create Record
        item = CKRecord(recordType: RecordTypeItems)

        //Initialization Reference
        guard let recordID = list?.recordID else { return }
        let listReference = CKRecord.Reference(recordID: recordID, action: .deleteSelf)

        item?.setObject(listReference, forKey: "list")
    }

    item?.setObject(name, forKey: "name")

    //Save Record
    privateDatabase.save(item!) { (record, error) in
        DispatchQueue.main.sync {
            self.processResponse(record: record, error: error)
        }
    }
}

获取方法

var list: CKRecord!
var items = [CKRecord]()

private func fetchItems() {
    //Fetch Private Database
    let privateDatabase = CKContainer.default().privateCloudDatabase

    //Initialize Query
    guard let recordID = list?.recordID else { return }
    let reference = CKRecord.Reference(recordID: recordID, action: .deleteSelf)
    let query = CKQuery(recordType: RecordTypeItems, predicate: NSPredicate(format: "list == %@", [reference]))


    //Configure Query
    query.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]

    //Peform Query
    privateDatabase.perform(query, inZoneWith: nil) { (records, error) in
        DispatchQueue.main.sync {
            self.processResponseForQuery(records: records, error: error)
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在创建查询以检索引用列表的项目的地方,谓词格式字符串中的列表引用是否应在数组内?如果您创建像item?.setObject(listReference, forKey: "list")这样的项目引用,CloudKit就会将list字段推断为单个CKRecord.Reference,因此查询将是:

let query = CKQuery(recordType: RecordTypeItems, predicate: NSPredicate(format: "list == %@", reference))