AlertController在保存时不保存textField文本,仅编辑

时间:2016-01-29 15:50:27

标签: ios swift uialertcontroller

我有一个带有textField的alertController。用户将他们的数据输入到textField并点击" set"。然后应该创建项目并将输入的文本保存为我设置的属性。但是,在创建项目时,textField传递为nil。在重新打开并再次保存项目之前不会保存它(提示alertController在textField中请求数据)。为什么不第一次保存呢?

saveButton被迫:

@IBAction func saveButton(sender: AnyObject) {
    if (item?.slminqty == nil) {
    let alert = UIAlertController(title: "Minimun Qty.", message: "Please set minimun qty. for pantry.", preferredStyle: UIAlertControllerStyle.Alert)

        alert.addTextFieldWithConfigurationHandler { (textField: UITextField!) -> Void in
        textField.placeholder = "Minimun Qty."
        textField.keyboardType = .NumbersAndPunctuation
        textField.clearButtonMode = UITextFieldViewMode.WhileEditing
    }

    alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: {saveitem}()))
    alert.addAction(UIAlertAction(title: "Set", style: UIAlertActionStyle.Default, handler: {(action) -> Void in
        let textField = alert.textFields![0].text!
        self.item?.slminqty = textField

       self.saveitem(self)}))

        self.presentViewController(alert, animated: true, completion: nil)

    }else{

        if item != nil {
            edititems()

        } else {
            createitems()
        }
        print(item?.slminqty)

        dismissVC()
    }

    }

保存功能:

func saveitem(sender: AnyObject) {

    if item != nil {
        edititems()

    } else {
        createitems()
    }
    print(item?.slminqty)

    dismissVC()
}

创建功能:

func createitems() {

    let entityDescription = NSEntityDescription.entityForName("List", inManagedObjectContext: moc)

    let item = List(entity: entityDescription!, insertIntoManagedObjectContext: moc)

    item.slitem = slitem.text
    item.sldesc = sldesc.text
    item.slqty = slqty.text
    item.slprice = slprice.text
    item.slist = true
    item.slcross = false

    if slitem.text == nil{
        createitems()

    }else{
        edititems()
    }

    do {
        try moc.save()
    } catch _ {
        return
    }
}

编辑功能:

func edititems() {
    item?.slitem = slitem.text!
    item?.sldesc = sldesc.text!
    item?.slqty = slqty.text!
    item?.slprice = slprice.text!

    do {
        try moc.save()
    } catch {
        return
    }
}

如果创建和编辑都相同(slcross和slist除外),为什么在创建项目时不保存数据?

1 个答案:

答案 0 :(得分:1)

修改,请参阅我的pull reqest,我对您的代码进行了一些更改。以及一些评论。

我认为这一行存在问题:

 self.item?.slminqty = textField

self.item可能是零。你应该确保第一项不是零。

如果这是零,您可以尝试创建项目。像:

if self.item == nil {
   //create item. 
   self.acreateItems()
   // after creating the item just test its value.
    print("item was nil so we just created it.\nIts value not is \(self.item)")
}
self.item?.slminqty = textField