尝试解包领域对象时出错

时间:2018-05-23 11:20:22

标签: ios swift realm

当我尝试使用其中一个Realm对象的数据时,我遇到了以下问题 我有一个错误:

  

线程1:致命错误:在解包可选值时意外发现nil

我感到困惑,因为当我尝试在调试控制台上手动完成时,一切正常

  

(lldb)打印餐?.mealName   (String?)$ R0 =" Krem buraczany"

我将附上整个代码,并显示出现哪个行错误

领域对象:

import UIKit
import RealmSwift

class Meal: Object {

@objc dynamic var mealID : String = ""
@objc dynamic var mealName : String = ""
var ingredients = List<String>()
var mealDescription = List<String>()
@objc dynamic var kcal : Int = 0
@objc dynamic var preparingTime : Int = 0
@objc dynamic var imageName : String = ""

convenience init(mealID: String, mealName: String, kcal: Int, preparingTime: Int, imageName: String) {
    self.init()

    self.mealID = mealID
    self.mealName = mealName
    self.kcal = kcal
    self.preparingTime = preparingTime
    self.imageName = imageName

}

override static func primaryKey() -> String? {
    return "mealID"
}

}

通过segue发送数据:

    @IBAction func ideaForMealButtonPressed(_ sender: UIButton) {
    performSegue(withIdentifier: "ideaForMeal", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let destinationVC = segue.destination as! IdeaForMeal
    destinationVC.randomMeal = getRandomMeal()

}

func getRandomMeal() -> String {

    var mealsCount = realm.objects(Meal.self).count
    mealsCount += 1
    let randomMealID = arc4random_uniform(UInt32(mealsCount))
    print (randomMealID)

    return String(randomMealID)

}

接收器:

//Global Variables
let realm = try! Realm()
var randomMeal : String? {
    didSet {
        let selectedMeal = downloadMealData(mealID: randomMeal!)
        setUIForMeal(meal: selectedMeal)
    }
}


override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround()

}

//Background Operations

func downloadMealData(mealID: String?) -> Meal? {

    let currentMeal = realm.object(ofType: Meal.self, forPrimaryKey: mealID)
    return currentMeal

}

func checkPositionOfTopIngredientsLabel() -> CGFloat {

    let maxY = ingredientsTopLabel.frame.maxY
    return maxY

}

func setUIForMeal(meal: Meal?) {

    mealNameLabel.text = meal!.mealName // Error!
    mealImage.image = UIImage(named: meal!.imageName)
    preparingTimeLabel.text = String(meal!.preparingTime)
    kcalLabel.text = String(meal!.kcal)

}

谢谢!

BR IMAT

1 个答案:

答案 0 :(得分:0)

该错误与Realm无关。这是一个非常常见的生命周期错误。

在目标视图控制器中设置randomMeal会触发didSet观察者。观察者将访问尚未连接的IBOutlet

解决方案是在viewDidLoad

中运行代码
var randomMeal = ""

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround()
    if !randomMeal.isEmpty {
        let selectedMeal = downloadMealData(mealID: randomMeal)
        setUIForMeal(meal: selectedMeal)
    }

}