-2

I am experiencing a strange crash in my app while updating a label.text with a string from a variable that does have a value.

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")
                }
            }

Some screenshots:

Code

Console

I can't figure out what's going on here

Wizzardzz
  • 781
  • 1
  • 9
  • 32

2 Answers2

1

You are assigning bitcoinPriceLabel value before it is being drawn.

It is not the value.

Bista
  • 7,869
  • 3
  • 27
  • 55
0

You are initializing a new instance of MainViewController in the line where the error occurs.

View controllers don't have their outlets installed directly after an initialization, so bitcoinPriceLabel will be nil.

Change MainViewController() to the instance of it you're currently using, so it will reference the label of the view controller that is visible in your application (in this example, mainVc):

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

Learn more about the view controller lifecycle here.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
  • I can't remove `()` without getting `Instance member 'bitcoinPriceLabel' cannot be used on type 'MainViewController'` – Wizzardzz Jan 12 '18 at 13:26
  • My code is in another file because the function is too large to be in the 'MainViewController' – Wizzardzz Jan 12 '18 at 13:30
  • If that's the case, you should pass a reference of the used instance of MainViewController to the class this code is in. [Learn more about passing data between view controllers here.](https://stackoverflow.com/q/5210535/3151675) – Tamás Sengel Jan 12 '18 at 13:32
  • Can't I just store the values in a static var and update the labels from the MainViewController? I am sorry but this method was working before I changed the way I fetch the data from the API so I am really struggling understanding what's wrong now. – Wizzardzz Jan 12 '18 at 13:50
  • 1
    Possibly. Show the code for the definition of MainViewController as this affects how you access it. – Upholder Of Truth Jan 12 '18 at 14:04