从 CloudKit 中的 CKRecord.Reference 获取价值
Posted
技术标签:
【中文标题】从 CloudKit 中的 CKRecord.Reference 获取价值【英文标题】:Get value from CKRecord.Reference in CloudKit 【发布时间】:2020-11-25 13:48:16 【问题描述】:我有 2 个记录类型:“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!)
但出现错误:
由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[
valueForUndefinedKey:]:此类与键 userName 的键值编码不兼容。”
感谢任何帮助和建议。
【问题讨论】:
【参考方案1】:我假设你是这样保存参考的:
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)
【讨论】:
以上是关于从 CloudKit 中的 CKRecord.Reference 获取价值的主要内容,如果未能解决你的问题,请参考以下文章
为啥我不能从 Xcode 或 CloudKit Dashboard 查询 CloudKit?
如何使用objective-c从CloudKit中的资产字段中检索图像
从 CloudKit 和 Swift 3 中的表/RecordType 计算字段的总和,例如特定 Customer_Name 的 Bill_Amount