Swift NSDictionary 值 return 即使在检查值存在于内部之后也为零
Swift NSDictionary values return nil even after checking values exist inside
我不确定为什么我的 NSDictionary 值在我将 firebase 快照分配给它并看到值在那里之后打印 "employeeUserData" 后仍然返回 nil。当我 运行 我的应用程序测试我是否可以从 NSDictionary 中提取字符串时,它说它是一个 nil 值。我以前使用过这段代码并且这种方法有效,不知道为什么突然它不起作用并返回 nil,是的,这是编码,这样的事情一直在发生,大声笑只是想了解为什么这个特殊问题是发生。谢谢。
let employeeUid = Auth.auth().currentUser?.uid
var employeeUserData: NSDictionary?
override func viewDidLoad() {
super.viewDidLoad()
Database.database().reference().child("employees").child(employeeUid!).child("Business").observe(DataEventType.value, with: { (snapshot) in
print("VALUE CHANGED IN USER_PROFILES")
self.employeeUserData = snapshot.value as? NSDictionary
//store the key in the users data variable
self.employeeUserData?.setValue(employeeUid, forKey: "uid")
print(self.employeeUserData!)
}) { (error) in
print(error.localizedDescription)
}
printUserData()
}
func printUserData() {
print(self.employeeUserData!["businessuid"] as! String)
}
这是因为您是从数据库中异步获取数据(这是正确的做法),但您是同步调用 printUserData
。因此, printUserData()
在获取和设置实际数据之前被调用。
当您 运行 这段代码时,请注意您看到 printUserData()
中的打印在 print(self.employeeUserData)
被调用之前执行。
我不确定为什么我的 NSDictionary 值在我将 firebase 快照分配给它并看到值在那里之后打印 "employeeUserData" 后仍然返回 nil。当我 运行 我的应用程序测试我是否可以从 NSDictionary 中提取字符串时,它说它是一个 nil 值。我以前使用过这段代码并且这种方法有效,不知道为什么突然它不起作用并返回 nil,是的,这是编码,这样的事情一直在发生,大声笑只是想了解为什么这个特殊问题是发生。谢谢。
let employeeUid = Auth.auth().currentUser?.uid
var employeeUserData: NSDictionary?
override func viewDidLoad() {
super.viewDidLoad()
Database.database().reference().child("employees").child(employeeUid!).child("Business").observe(DataEventType.value, with: { (snapshot) in
print("VALUE CHANGED IN USER_PROFILES")
self.employeeUserData = snapshot.value as? NSDictionary
//store the key in the users data variable
self.employeeUserData?.setValue(employeeUid, forKey: "uid")
print(self.employeeUserData!)
}) { (error) in
print(error.localizedDescription)
}
printUserData()
}
func printUserData() {
print(self.employeeUserData!["businessuid"] as! String)
}
这是因为您是从数据库中异步获取数据(这是正确的做法),但您是同步调用 printUserData
。因此, printUserData()
在获取和设置实际数据之前被调用。
当您 运行 这段代码时,请注意您看到 printUserData()
中的打印在 print(self.employeeUserData)
被调用之前执行。