在插入CoreData

时间:2018-06-26 12:29:34

标签: ios swift uitextfield swift4

我有4个UITextField和一个UIButton(保存按钮)。 当我按下Save按钮时,它应该将我在文本字段中拥有的内容添加到CoreData中,并在UITableView中填充数据。 但是问题是,当我没有在TextFields中放入任何内容时,按“保存”时,会将一个空对象添加到CoreData和UITableView中。

这是我的代码:

@IBOutlet weak var productNameTextfield: UITextField!

    @IBOutlet weak var productCategoryTextField: UITextField!

    @IBOutlet weak var productDescriptionTextfield: UITextField!

    @IBOutlet weak var productPriceTextfield: UITextField!

       // Func to insert data from TextFields into DB
        func insertProduct(){

            let product = Product(context: context)
            let productUUID = UUID().uuidString
            product.id = productUUID

            if (productNameTextfield.text?.trimmingCharacters(in: .whitespaces).isEmpty)! {
                showAlertWith(title: "Name required", message: "Product name is required !")
            }
            else if (productCategoryTextField.text?.trimmingCharacters(in: .whitespaces).isEmpty)! {
                showAlertWith(title: "Category required", message: "Product Category required !")
            }
            else if (productDescriptionTextfield.text?.trimmingCharacters(in: .whitespaces).isEmpty)! {
                showAlertWith(title: "Description required", message: "Product Description required !")
            }
            else if (productPriceTextfield.text?.trimmingCharacters(in: .whitespaces).isEmpty)! {
                showAlertWith(title: "Price required", message: "Product Price required !")
            }
            else{
                guard let productPrice = (productPriceTextfield.text ?? "").isEmpty ? "0.00" : productPriceTextfield.text else { return }
                product.name = self.productNameTextfield.text!
                product.category = self.productCategoryTextField.text!
                product.prodDescription = self.productDescriptionTextfield.text!
                product.price = Float(productPrice)!
                appDelegate.saveContext()
                resetAllFields()
                showAlertWith(title: "Done", message: "Product was added with success !")
            }
        }

这是我的CoreData:

enter image description here

这是我在界面上的错误:

enter image description here

任何想法都会对我有很大帮助! 谢谢!

1 个答案:

答案 0 :(得分:3)

一旦调用行Product(context: context),就会创建CoreData对象并将其插入到上下文中。将这些行移动到else块的开头:

    ...
} else {
    let product = Product(context: context)
    let productUUID = UUID().uuidString
    product.id = productUUID

    guard let productPrice = (productPriceTextfield.text ?? "").isEmpty ? "0.00" : productPriceTextfield.text else { return }
    ...