gpt4 book ai didi

swift - 如何删除CloudKit中的CKRecord和所有引用记录

转载 作者:行者123 更新时间:2023-11-30 11:38:37 31 4
gpt4 key购买 nike

我想删除父级 CKRecord 以及该记录的所有子级。创建父记录和子记录的方法如下所示:

func save() {
//Creating parent record

let parentRecord = CKRecord(recordType: "ParentRecord")
parentRecord["name"] = "BOO" as CKRecordValue

//Creating child record

let childRecord = CKRecord(recordType: "ChildRecord")
childRecord["name"] = "FOO" as CKRecordValue
let reference = CKReference(record: childRecord, action: CKReferenceAction.deleteSelf)

//ADDING Reference to parent record

parentRecord["referenceObject"] = reference as CKRecordValue

let operation = CKModifyRecordsOperation(recordsToSave: [parentRecord, childRecord], recordIDsToDelete: nil)
//([CKRecord]?, [CKRecordID]?, Error?) -> Void)
operation.modifyRecordsCompletionBlock = { records, recordIDs, error in
if error != nil {
print(error.debugDescription)
}
}
operation.queuePriority = .high
operation.qualityOfService = .background
let operationQueue = OperationQueue()
operationQueue.addOperations([operation], waitUntilFinished: false)
}

现在我想仅通过代码删除父记录。由于CKReferenceAction.deleteSelf,子记录应该被自动删除。函数“删除”如下所示:

func delete(recordName: String) {
let privateDB = CKContainer.default().privateCloudDatabase
let recordID = CKRecordID(recordName: recordName)
privateDB.delete(withRecordID: recordID) { (id, error) in
if error != nil {
print(error.debugDescription)
}
}
}

当我使用此delete方法时,我的记录正在从CloudKit数据库中删除,但子记录仍然存在,但我不存在知道为什么。有什么建议吗?

最佳答案

SOLUTION

如果我们想删除子记录,我们必须将父记录的引用添加到子记录。在上面的情况下,它应该看起来像这样:

    let privateDB = CKContainer.default().privateCloudDatabase

let parentRecord = CKRecord(recordType: "ParentRecord")
parentRecord["name"] = "FOO" as CKRecordValue

let childRecord = CKRecord(recordType: "ChildRecord")
childRecord["name"] = "BOO" as CKRecordValue

privateDB.save(parentRecord) { (record: CKRecord?, error: Error?) in
if error == nil {
if let responseRecord = record {
let reference = CKReference(record: responseRecord, action: CKReferenceAction.deleteSelf)
childRecord["referenceObject"] = reference as CKRecordValue
privateDB.save(childRecord, completionHandler: { (record, error) in
// DO SOMETHIG
})
}
}
}

在这种情况下,删除父记录使得子记录将被自动删除

关于swift - 如何删除CloudKit中的CKRecord和所有引用记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49467687/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com