CKRecord 获取键的值

CKRecord get value for key

我正在尝试根据用户的用户名获取用户的值。我能够使用以下方法获得正确的用户:

class func getByUsername(username: String, callback: (records: [CKRecord]) -> ()){
    getSummary(NSPredicate(format: "Username == %@", username)){(records: [CKRecord]) -> Void in
        callback(records: records)
    }
}

class func getSummary(predicate: NSPredicate, callback: (records: [CKRecord]) -> ()){
    let query = CKQuery(recordType: "UserInfo", predicate: predicate)
    let queryOperation = CKQueryOperation(query: query)
    queryOperation.desiredKeys = ["ID"]

    var records = [CKRecord]()
    queryOperation.recordFetchedBlock = {record in records.append(record)}
    queryOperation.queryCompletionBlock = {_ in callback(records: records)}

    CKContainer.defaultContainer().publicCloudDatabase.addOperation(queryOperation)
}

然后我可以通过调用获得正确的记录:

getByUsername("Username"){(records: [CKRecord]) -> Void in
  var record: CKRecord = records[0]
}

我也可以使用

得到正确的ID
var id: String = record.recordID.recordName

所以我知道我正在获取正确的记录,但是,当我尝试从记录中获取值时,例如用户的电子邮件,nil 是 returned:

var email: String = record.objectForKey("Email") as String

我也试过:

record.valueForKey("Email")
record.valueForKeyPath("Email")

当我打印 record.allKeys() 时,我得到一个空数组 [],当我打印 record.allTokens() 时,我得到一个 return of nil

我是否没有正确地从记录中获取值,或者我是否必须查询数据库以获取我想使用记录 ID 获取的每个值?根据 the documentation 所说:

A CKRecord object is a dictionary of key-value pairs that you use to fetch and save the data of your app.

我假设我不必查询数据库以获取我想要获取的每个值,并且这些值会在从 iCloud 获取后自动插入到 CKRecord

当你漏掉这一行时:

queryOperation.desiredKeys = ["ID"]

查询将 return 所有字段。

您没有收到 ID 字段可能是因为它是一个可以使用

访问的系统字段
var ID = record.recordID.recordName