首页 > 解决方案 > 如何在 customTableViewCell 中获取 UITextField 的字符串并将其保存到 coreData?

问题描述

let  save  = UIApplication.shared.delegate as! AppDelegate
var price =  " "
// config cell here
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "priceCell", for: indexPath) as! PriceTableViewCell
    cell.priceTextField.text = numberFromKeyPad
    price = cell.priceTextField.text!
    return cell
}

在这里它将价格保存到 coreData

@IBAction func saveButtonClicked(_ sender: UIButton) {
    save.check.price = Int64 (price)!//here i have this error :Fatal error: Unexpectedly found nil while unwrapping an Optional val
    PersistentService.saveContext()
    print(NSHomeDirectory())
}

核心数据中的这个错误是什么?

标签: swiftxcodecore-datatableview

解决方案


Ok Declare the Price variable like 

var price:String?

    before assigning the value to price check whether pricetextfield contains the value or not

if let priceValue = cell.priceTextField.text {
   price =  priceValue
}
and again before calling save.check.price = Int64 (price)! check for value

if let price = price {
   save.check.price = price
}

推荐阅读