4

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

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会返回:

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

我也试过:

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

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

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

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

I would assume that I do not have to query the database for every value that I would like to get, and that the values are automatically inserted into the CKRecord upon getting it from iCloud

4

1 回答 1

4

When you leave out the line:

queryOperation.desiredKeys = ["ID"]

the query will return all the fields.

That you did not receive the ID field is probably because its a system field which can be accessed using

var ID = record.recordID.recordName 
于 2015-01-06T08:09:01.117 回答