从 CloudKit 中的 CKRecord.Reference 获取值

Get value from CKRecord.Reference in CloudKit

我有 2 个 recordType:“userDetails”和“request”,其中“request”中的一个字段引用“userDetails”。我想知道如果我从“请求”中获取记录以获取引用字段,然后从引用中获取仅在“userDetails”中可用的其余值(例如用户名),这可能吗?或者有什么方法可以在不进行其他数据获取的情况下实现这一点?

我试过这个:

CKContainer.default().publicCloudDatabase.fetch(withRecordID: CKRecord.ID(recordName: "0A38D024-C191-436E-8622-AE7527805CE8")) { (fetched, error) in
   if fetched != nil {
      let a = fetched?.value(forKey: "requesterReferenceId") as? CKRecord.Reference
      let b = a?.recordID.value(forKey: "userName") as? String
      print(b!)
  }
}

但是出现错误:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<CKReference 0x600002034280> valueForUndefinedKey:]: this class is not key value coding-compliant for the key userName.'

感谢任何帮助和建议。

我假设你是这样保存参考的:

let userDetail = CKRecord(recordType: "UserDetail")
let request = CKRecord(recordType: "Request")
let reference = CKRecord.Reference(recordID: userDetail.recordID, action: .deleteSelf)
request["requesterReferenceId"] = reference as CKRecordValue

您是否尝试过使用获取的引用作为谓词?

let publicDatabase = CKContainer.default().publicCloudDatabase
publicDatabase.fetch(withRecordID: CKRecord.ID(recordName: "0A38D024-C191-436E-8622-AE7527805CE8")) { (fetched, error) in
    if fetched != nil {
        if let reference = fetched?.value(forKey: "requesterReferenceId") as? CKRecord.Reference {
            let predicate = NSPredicate(format: "recordID == %@", reference)
            let query = CKQuery(recordType: "UserDetail", predicate: predicate)
            let queryOperation = CKQueryOperation(query: query)
            queryOperation.desiredKeys = ["list any keys you want to fetch here"]
            queryOperation.recordFetchedBlock = { (record: CKRecord?) -> Void in
                if let record = record {
                    print(record)
                }
                
            }
            
            queryOperation.queryCompletionBlock = { (cursor: CKQueryOperation.Cursor?, error: Error?) -> Void in
                if let error = error {
                    print(error)
                    return
                }
                
            }
            publicDatabase.add(queryOperation)
        }
    }
}