【发布时间】:2017-10-07 07:58:27
【问题描述】:
我希望用户添加好友。然而,每当我点击 addFriend 按钮时,我都会得到一个带有thread 1 的断点。除了11db,没有其他错误信息。
我现在发现“otherUser”的NSDictionary 的值为none。这就是一切都不起作用的原因。但是我不知道为什么会这样。在同一个 NSDictionary 中,我得到了用户名和个人资料图片。那为什么是零呢?
var otherUser: NSDictionary?
override func viewDidLoad() {
super.viewDidLoad()
databaseRef.child("user").child(self.otherUser?["uid"] as! String).observe(.value, with: { (snapshot) in
let uid = self.otherUser?["uid"] as! String
self.otherUser = snapshot.value as? NSDictionary
self.otherUser?.setValue(uid, forKey: "uid")
}) { (error) in
print(error.localizedDescription)
}
}
@IBAction func addFriend(_ sender: Any) {
if self.befreunden.titleLabel?.text == "Als Freund hinzufügen" {
let friendRef = "befreundet/\(self.loggedinUSerData?["uid"] as! String)/\(self.otherUser?["uid"] as! String)"
let BefreundenData = ["username":self.otherUser?["username"] as? String,
"ProfilePic":self.otherUser?["urltoImage"] as! String!]
let childUpdats = [friendRef:BefreundenData]
databaseRef.updateChildValues(childUpdats)
}else {
FreundeAnzahl = self.otherUser?["AnzahlFreunde"] as! Int + 1
}
}
编辑:
我刚刚发现,otherUser 的 NSDictionary 具有 viewdidLoad 中所需的所有值。但是,一旦我在 addFriend 函数中调用 otherUser 的 uid,它就会返回 nil 值。 为什么会这样?
【问题讨论】:
-
你的代码在哪一行停止了?
-
它在 let FriendRef 中停止。
-
它停止是因为你强制解开一个 nil 的可选。如果没有看字典,除了告诉你不要强制解包选项之外,没有其他办法可以回答这个问题。它所做的只是导致疼痛和错误。 (比如这个)。
-
但为什么是可选的 nil 呢?正如我在 viewdidload 中所说,它有一个可选值,我可以强制解包而不会出现任何问题
标签: ios firebase swift3 firebase-realtime-database nsdictionary