gpt4 book ai didi

ios - 尝试解开 Realm 对象时出错

转载 作者:行者123 更新时间:2023-11-30 11:28:28 26 4
gpt4 key购买 nike

当我尝试使用 Realm 对象之一的数据时,出现以下问题我有一个错误:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

我很困惑,因为当我尝试在调试控制台上手动执行此操作时,一切正常

(lldb) print meal?.mealName (String?) $R0 = "Krem buraczany"

我将附上完整的代码并告诉您错误出现在哪一行

Realm 对象:

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)

}

谢谢!

BRiMat

最佳答案

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

在目标 View Controller 中设置randomMeal会触发didSet观察者。观察者将访问尚未连接的 IBOutlet

解决方案是在viewDidLoad中运行代码

var randomMeal = ""

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

}

关于ios - 尝试解开 Realm 对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50487085/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com