无法将用户 ID 指定为参考

Cannot assign userID as reference

我正在尝试为一条记录分配几个不同的属性。

日期和姓名工作正常。 Avatar 是对另一条记录的引用,也可以正常工作。但是后来我尝试为用户分配一个引用,我得到了 slamyyourheadagainstthescreen 的时刻。这是我的代码:

var avatarID : CKRecordID!
var userID : CKRecordID!

//avatarID has been assigned value in another function
daMainUser.setObject(CKReference(recordID: avatarID! as CKRecordID, action: CKReferenceAction.None), forKey: "avatar")
println("this is avatarID: \(avatarID!)")

containerY.fetchUserRecordIDWithCompletionHandler{
            userRecordID, error in
            if error != nil {
                println("error")
            } else {
                println("gettin close")
                self.userID = userRecordID
                println("this is userID: \(self.userID!)")
                daMainUser.setObject(CKReference(recordID: self.userID! as CKRecordID, action: CKReferenceAction.None), forKey: "ownerOfThat")
                }
            }
        publicDatabase.saveRecord(daMainUser) {
            record, error in
            if error != nil {
                println(error.localizedDescription)
            } else {
                println(record.objectForKey("nickName") as String + " recorded")
            }
        }

当我保存 daMainUser 并查看 apple 仪表板时,我看到 "avatar" 引用已成功保存但未 "ownerOfThat"。这是我从控制台得到的:

this is avatarID: <CKRecordID: 0x7a83d3d0; 79CE1EDC-593D-4AE0-8433-8488F857A302:(_defaultZone:__defaultOwner__)>
gettin close
this is userID: <CKRecordID: 0x7a863910; _8a15e8e6138ba234b62f25cfd3eeb66e:(_defaultZone:__defaultOwner__)>
John Doe recorded

这让我相信 userID 和来自另一条记录的 ID 不是同一种 ID。但我不知道为什么以及该怎么做。 提前谢谢你

我认为你的括号错了。应该是:

var avatarID : CKRecordID!
var userID : CKRecordID!

//avatarID has been assigned value in another function
daMainUser.setObject(CKReference(recordID: avatarID! as CKRecordID, action: CKReferenceAction.None), forKey: "avatar")
println("this is avatarID: \(avatarID!)")

containerY.fetchUserRecordIDWithCompletionHandler{
            userRecordID, error in
            if error != nil {
                println("error")
            } else {
                println("gettin close")
                self.userID = userRecordID
                println("this is userID: \(self.userID!)")
                daMainUser.setObject(CKReference(recordID: self.userID! as CKRecordID, action: CKReferenceAction.None), forKey: "ownerOfThat")
            }
        publicDatabase.saveRecord(daMainUser) {
            record, error in
            if error != nil {
                println(error.localizedDescription)
            } else {
                println(record.objectForKey("nickName") as String + " recorded")
            }
        }
     }

现在您可以在获取记录之前保存记录。