【问题标题】:Strange `Fatal error: Unexpectedly found nil` but optional DOES have a value奇怪的“致命错误:意外发现 nil”,但可选的确实有值
【发布时间】:2018-01-12 13:10:00
【问题描述】:

我的应用程序在使用具有值的变量中的字符串更新label.text 时遇到了奇怪的崩溃。

if WalletViewController.currencyUSD == true {
                MainViewController.bitcoinDoublePrice = Double((bitcoinInfo.raw.btc.usd?.price)!)
                print("MainViewController.bitcoinDoublePrice =", MainViewController.bitcoinDoublePrice)
                let formatter = NumberFormatter()
                formatter.numberStyle = .currency
                formatter.locale = Locale(identifier: "en_US")
                let bitcoinStringPrice = formatter.string(from: NSNumber(value: MainViewController.bitcoinDoublePrice))
                print("bitcoinStringPrice =", bitcoinStringPrice!)
                if let bitcoinPrice = bitcoinStringPrice {
                    MainViewController().bitcoinPriceLabel.text = String(bitcoinPrice + ", ") //<<<Thread 3: Fatal error: Unexpectedly found nil while unwrapping an Optional value
                } else {
                    print("bitcoinPrice = nil")
                }
            }

一些截图:

Code

Console

我不知道这里发生了什么

【问题讨论】:

  • 有些截图可以说出一百万个单词,但这些不是其中之一。请以文本形式包含您的代码。
  • 你需要哪一部分?
  • 截取代码不是一个好主意,只需将其复制并粘贴到问题中即可。这样人们就可以更轻松地复制您正在做的事情。
  • @ColGraff 不仅如此,帖子的可搜索性也会更好。
  • 我用代码编辑了问题

标签: swift crash


【解决方案1】:

您在绘制之前分配bitcoinPriceLabel 值。

这不是价值。

【讨论】:

    【解决方案2】:

    您正在发生错误的行中初始化MainViewController一个新实例

    视图控制器在初始化后没有直接安装它们的出口,所以bitcoinPriceLabel 将为零。

    MainViewController() 更改为您当前使用的实例,因此它将引用在您的应用程序中可见的视图控制器的标签(在本例中为mainVc):

    mainVc.bitcoinPriceLabel.text = String(bitcoinPrice + ", ")
    

    详细了解视图控制器生命周期here

    【讨论】:

    • 如果没有得到Instance member 'bitcoinPriceLabel' cannot be used on type 'MainViewController',我无法删除()
    • 我的代码在另一个文件中,因为函数太大而不能在'MainViewController'中
    • 如果是这种情况,您应该将使用的 MainViewController 实例的引用传递给此代码所在的类。Learn more about passing data between view controllers here.
    • 我不能将值存储在静态变量中并从 MainViewController 更新标签吗?很抱歉,但在我更改从 API 获取数据的方式之前,这种方法已经奏效,所以我现在真的很难理解出了什么问题。
    • 可能。显示 MainViewController 定义的代码,因为这会影响您访问它的方式。
    猜你喜欢
    • 1970-01-01
    • 2016-01-26
    • 2023-03-11
    • 1970-01-01
    • 2016-02-29
    • 2020-09-19
    相关资源
    最近更新 更多