ios - Swift iOS - 即使存在有效数据,Firebase 是否有可能破坏数据并返回零值?

标签 ios swift firebase null crash

在我将数据发送到 Firebase 之前,我会确保某个值确实存在。在我的应用程序的几个不同点,我从 Firebase 数据库中提取数据。在 Firebase 检索数据时是否有可能出错并返回 nil 而不是实际数据?

Firebase 基本上可以破坏有效数据并以 nil 值的形式返回吗?

nameRef?.observeSingleEvent(of: .value, with: {
            (snapshot) in

            if let dict = snapshot.value as? [String:Any]{

                //100% these have valid data
                //but if either of these get corrupted and returned as nil there will be a crash
                let firstName = dict["firstName"] as? String
                let lastName = dict["lastName"] as? String

                self.firstNameLabel.text! = firstName!
                self.lastNameLabel.text! = lastName!            
            }
}

我知道我可以使用 if let 来防止崩溃,但我想知道是否有必要这样做?与 firstName 和 lastName 相比,我有更多的数据被提取,我将不得不在所有地方使用 if let。尽管这样做是安全的,但它会在我的应用程序中添加大量代码。如果不需要,我不会使用它。

if let firstName = firstName{....
if let lastName = lastName{....

这是我第一次构建应用程序,之前我从未在团队中工作过或与团队合作过,所以我不知道这样的问题的答案。

最佳答案

不,当您从 Firebase 检索值时,当值不在您的缓存中时,您确定您从数据库中正确获取了值。我在这里看到的一个常见错误是,它们在 appDelegate 中具有持久性,并且它们在捕获 singleEvent 之前不会同步数据库,就像您正在做的那样。使用 childAdded、childRemoved 等时,数据库始终保持同步,因此您不必调用 keepSynched/关闭持久性。

下面的代码看起来更干净、更安全、更易于理解。我只是添加了默认值。

nameRef?.observeSingleEvent(of: .value, with: {
            (snapshot) in
                let values = snapshot.value as? NSDictionary
                self.firstNameLabel.text! = dict["firstName"] as? String ?? "No first name given"
                self.lastNameLabel.text! = dict["lastName"] as? String ?? "No last name given"
}

如果您在 appDelegate 中有持久性,请在使用 observeSingleEvent 捕获数据之前调用 nameRef?.keepSynced(true)。不调用它会导致奇怪的快照值,比如这个:How to retrieve data from firebase using Swift?

关于ios - Swift iOS - 即使存在有效数据,Firebase 是否有可能破坏数据并返回零值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45286546/

相关文章:

json - POST 请求后在 swift 模型中访问值的问题

ios - iOS:如何在TabBar的UIImage中将特定颜色替换为另一种颜色(选择和取消选择)?

swift - 过滤数据快照 Swift Firebase

ios - 在 iOS 下操作现有 PDF 文档的最佳方法是什么?

ios - 如何 UI 测试 UICollectionViewCell didSelect

ios - 如何为 UIPageViewController 启用 Voice Over 3 手指滑动手势

ios - 从标签栏 Controller 返回查看 Controller

ios - 计算后显示数字?

java - 从 Firebase 数据库读取特定数据

ios - Firebase-找不到配置文件 : 'GoogleService-Info.plist'