意外在应用首次加载时发现无效

时间:2018-12-28 13:46:57

标签: swift realm

当用户第一次加载我的应用程序时,它由于解开了一个可选的nil值而崩溃,但在下次加载时完美崩溃了

我首先认为这是由于在网络请求之后推送了通知,我尝试在realm.add(object,update:true)之后推送通知,但这似乎不是问题。

这来自我的网络课程:

func updateBitcoinData(bitcoinJSON: JSON){

    print("Parsing the JSON")
    let receivedData = Rates()
    receivedData.btcUSD =  bitcoinJSON["bpi"]["USD"]["rate"].string!
    receivedData.btcGBP =  bitcoinJSON["bpi"]["GBP"]["rate"].string!
    receivedData.btcEUR =  bitcoinJSON["bpi"]["EUR"]["rate"].string!

    receivedData.usdSymbol = bitcoinJSON["bpi"]["USD"]["symbol"].string!.html2String
    receivedData.gbpSymbol = bitcoinJSON["bpi"]["GBP"]["symbol"].string!.html2String
    receivedData.eurSymbol = bitcoinJSON["bpi"]["EUR"]["symbol"].string!.html2String

    receivedData.chartName = bitcoinJSON["chartName"].string!
    receivedData.timeUpdated = receivedData.convertUTCDateToLocalDate(dateToConvert: bitcoinJSON["time"]["updated"].string!)

    do {
        try realm.write {
            realm.add(receivedData, update: true)
            DispatchQueue.main.async {
                NotificationCenter.default.post(name: .ReceivedBitcoinData, object: nil)
            }
        }
    } catch {
        print("Error saving rates, \(error)")
    }

这是我在ViewController类中所做的:

override func viewWillAppear(_ animated: Bool) {
    loadRates()
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.bitcoinDataReceived(_:)), name: NSNotification.Name(rawValue: "ReceivedBitcoinData"), object: nil)
}


@objc func bitcoinDataReceived(_ notification: Notification) {
    updateBitcoinData()
}

@objc func updateBitcoinData() {

    bitcoinPriceLabel.text = rates!.usdSymbol + rates!.btcUSD
    chartName.text = rates?.chartName
    timeUpdated.text = rates?.timeUpdated
}

该错误在第一次加载时抛出该行,它崩溃了,但是正如我在第二次加载中提到的那样,它可以正常工作

   bitcoinPriceLabel.text = rates!.usdSymbol + rates!.btcUSD

1 个答案:

答案 0 :(得分:1)

之所以发生这种情况,是因为您试图在将数据保存到Realm数据库之前对其进行访问。您可以使用guard避免崩溃,例如:

@objc func updateBitcoinData() {
    guard let rates = rates else{return}
    bitcoinPriceLabel.text = rates.usdSymbol + rates.btcUSD
    chartName.text = rates.chartName
    timeUpdated.text = rates.timeUpdated
}