简体   繁体   中英

Saving textfield value altered by textFieldDidEndEditing won't save in core data?

I am using the following to update a amountVAT based on textfield totalAmountInc

func textFieldDidEndEditing(textField: UITextField) {
    if totalAmountInc != nil {
        let tmpVAT = Double(totalAmountInc.text!)
        let valueVAT = getVATValue(tmpVAT!)

        //textfield2
        amountVAT.text = String(valueVAT)
    }
}

But now the value won't save (using Core Data)?

When i directly enter a amountVAT value it will be saved.

Saving process looks like

func newItem(){

    let context = self.context
    let ent = NSEntityDescription.entityForName("List", inManagedObjectContext: context)


    let nItem = List(entity: ent!, insertIntoManagedObjectContext: context)
    let numberFormatter = NSNumberFormatter()

    nItem.amountVAT = numberFormatter.numberFromString(amountVAT.text!)
    .....more values
    nItem.invoiceImage = UIImagePNGRepresentation(imageHolder.image!)

    do {
     try context.save()
    } catch {
        print(error)
    }
}
func saveValues(sender: AnyObject) {

        if nItem != nil {
            editItem()
        } else {
            newItem()
        }

        dismissVC()
    }

You need to examine what the variable you are trying to save to Core Data contains. Set a breakpoint and see where you made the mistake.

In your code sample, there are a number of issues. For example, in textFieldDidEndEditing the text field in question is passed as the textField variable - no reason to refer to your instance variable and check for nil . (Perhaps you intended to check if the text property is nil ? It is preferable to initialize it to "" and not bother with this check. You are not explaining what getVATValue does, presumably just calculating a percentage. A function seems overkill for something trivial as that (and it makes your code less readable).

Check what the result of Double(textField.text!) is. It is likely that you find some problem with the initialization of the Double value.

Also, it does not make sense to put the value into the VAT text field, and then at save time re-convert it into a number to save in Core Data. You are using an UI element to hold value (in an inconvenient format). Instead, you should be using variables of type Double to hold the values you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM