[英]Found nil when unwrapping optional value in core data
I've been trying to address this issue for a few days and it seems I'm only going in circles. 几天来我一直在努力解决这个问题,看来我只是转圈而已。
I'm adding data to core data by tapping on tableView
cells and then displaying the items on another tableView
. 我通过点击
tableView
单元格,然后在另一个tableView
上显示项目,将数据添加到核心数据中。
That works great, the problem is this: 效果很好,问题是这样的:
When I click on the other table view rows, to be able to see the item with all the other values stored in core data, I get 当我单击其他表格视图行时,为了能够看到包含所有其他值存储在核心数据中的项目,我得到
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value on the showMeTheGoodiesTwo(entry: myCart) line
...Inside viewDidLoad
. ...在
viewDidLoad
内部。 But I do not know why that's happening, as the entity is not empty. 但是我不知道为什么会这样,因为实体不是空的。
Here's the code of the view controller where I want to display the item's details. 这是我要在其中显示项目详细信息的视图控制器的代码。
Hope somebody can give me a hand. 希望有人能帮到我。
Cheers! 干杯!
import UIKit
class productQuantityViewController: UIViewController {
var myCart: Cart!
@IBOutlet weak var productImage: UIImageView!
@IBOutlet weak var productNameLabel: UILabel!
@IBOutlet weak var productDescriptionLabel: UILabel!
@IBOutlet weak var productAmountLabel: UITextField!
@IBOutlet weak var minusButton: UIButton!
@IBOutlet weak var plusButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
productImage.layer.cornerRadius = 10
minusButton.layer.cornerRadius = minusButton.frame.size.width/2
plusButton.layer.cornerRadius = plusButton.frame.size.width/2
showMeTheGoodiesTwo(entry: myCart)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showMeTheGoodiesTwo(entry: Cart) {
let name = entry.product
let quantity = entry.inventory
let description = entry.productDescription
let image = entry.productImage as Data?
let xNSNumber = quantity as NSNumber
productNameLabel!.text = name
productDescriptionLabel!.text = description
productAmountLabel!.text = xNSNumber.stringValue
productImage!.image = UIImage(data:image!)
print(productNameLabel.text as Any)
}
}
You need to change 你需要改变
var myCart: Cart!
To 至
var myCart: Cart?
? ? is use to make it optional.
用于使其可选。 And in viewDidLoad use
并在viewDidLoad中使用
if (myCart != nil){
showMeTheGoodiesTwo(entry: myCart)
} else {
//do something.
}
instead of 代替
showMeTheGoodiesTwo(entry: myCart)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.