代码之家  ›  专栏  ›  技术社区  ›  Lukas Bimba

Swift NSDictionary值即使在检查内部是否存在值后也返回nil

  •  1
  • Lukas Bimba  · 技术社区  · 6 年前

    我不知道为什么我的NSDictionary值在我将firebase快照分配给它并看到这些值存在后,即使在打印“employeeUserData”后仍返回nil。当我运行应用程序测试是否可以从NSDictionary中提取字符串时,它表示它是一个nil值。我以前用过这个代码,这个方法很有效,不知道为什么突然不起作用,返回nil,是的,这是编码,类似的事情一直在发生,lol只是想了解为什么会发生这个特殊的问题。谢谢

    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)
    }
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   AdamPro13    6 年前

    这是因为您正在异步地从数据库获取数据(这是正确的方法),但您正在调用 printUserData 同步地。因此,, printUserData() 在获取实际数据之前调用&设置

    printUserData() 先斩后奏 print(self.employeeUserData)