【问题标题】:Unexpectedly found nil while unwrapping an Optional value userdefaults [duplicate]在展开可选值 userdefaults 时意外发现 nil [重复]
【发布时间】:2021-04-13 18:04:55
【问题描述】:

在某些 iPhone 设备中并非全部发生崩溃,并且崩溃指出这一行并且消息显示“在展开可选值时意外发现 nil”。下面是快速代码

let location = userDefaults.object(forKey: "itemRes") as! [String] //this line is getting crash
requestModel.second_res_lat = location[0].description
requestModel.second_res_lon = location[1].description

【问题讨论】:

  • userDefaults.object(forKey: "itemRes") 无法转换为字符串数组
  • @aheze 有些设备没有崩溃,有些设备崩溃了,那么解决这个问题的解决方案是什么?
  • 不要强制解包,而是使用保护:let location = userDefaults.object(forKey: "itemRes") as? [String] else { /* No such setting, or it cannot be converted to array of strings */ return }
  • @MohammedNabil 试试print("itemRes is \(userDefaults.object(forKey: "itemRes"))") 看看它是什么。这可能不是你所期望的

标签: ios swift userdefaults


【解决方案1】:

这会崩溃,因为用户默认值要么没有值,即 nil,要么与 type 不同。最佳做法是始终使用可选绑定来消除异常的可能性。

这假定用户默认值将始终具有正确类型的值: let location = userDefaults.object(forKey: "itemRes") as! [String]

在继续之前尝试安全地解开该值:

if let location = userDefaults.object(forKey: "itemRes") as? [String] {
   requestModel.second_res_lat = location[0].description
   requestModel.second_res_lon = location[1].description
} else {
   // No location value found
}

OR

guard let location = userDefaults.object(forKey: "itemRes") as? [String] else { return }
requestModel.second_res_lat = location[0].description
requestModel.second_res_lon = location[1].description

这也可能有用: https://developer.apple.com/documentation/swift/optional

【讨论】:

  • 这真的很奇怪,我没有崩溃,但问题是某些设备的打印显示了一些价值,而某些设备的打印显示nil
  • @MohammedNabil 听起来这与您之前提出的问题有关。浏览您的代码并确保在设置之前不要尝试从用户默认值中读取"itemRes"。您可以在答案中使用最上面的代码,这肯定会阻止崩溃。您只需要找出为什么在未设置时会被读取。
猜你喜欢
  • 2014-12-27
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
  • 2017-01-23
  • 2016-10-18
相关资源
最近更新 更多