patrikbelis
patrikbelis

Reputation: 1360

CoreData TextField - unexpectedly found nil

I'm doing application with CoreData and textfields in tableview. In storyboard I have one textfield. textfield will multiply five times with different content in application. In navigation bar I have button that will save your written data. But when I press save button, application crash with error

enter image description here

IBOutlet is in the TableViewCell.swift. Code from image:

    @IBAction public func saveTapped(){

        if activeTextField.text.isEmpty {
            let alert = UIAlertView()
            alert.title = "Nevyplnené údaje"
            alert.message = "Musíš vyplniť všetky údaje o knihe."
            alert.addButtonWithTitle("Ok")
            alert.show()


        }
        let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let obsah: NSManagedObjectContext = appDel.managedObjectContext!
        let entity = NSEntityDescription.entityForName("List", inManagedObjectContext: obsah)
        var pridat = Model(entity: entity! , insertIntoManagedObjectContext: obsah)

        pridat.kniha = activeTextField.text
        pridat.autor = activeTextField.text
        pridat.rok = activeTextField.text
        pridat.vydavatelstvo = activeTextField.text
        pridat.strany = activeTextField.text

        obsah.
}

Here's full code:

http://pastebin.com/6LHqJW0w

Here's TableViewCell code:

http://pastebin.com/RAYTUcp6

I also tried

    let mfv = TableViewCell()

        if mfv.textField.text.isEmpty {
        let alert = UIAlertView()
        alert.title = "Nevyplnené údaje"
        alert.message = "Musíš vyplniť všetky údaje o knihe."
        alert.addButtonWithTitle("Ok")
        alert.show()
    }

Upvotes: 1

Views: 261

Answers (1)

pbasdf
pbasdf

Reputation: 21536

It looks like you are trying to set the value of activeTextField when the UITextField delegate methods are triggered. However, I can't see where you are setting your view controller to be the delegate for those textfields. I think you will need to add something to cellForRowAtIndexPath (or may be in the cell's configure method) to set the textField's delegate.

EDIT

I would amend your configure method to set the textField's delegate:

public func configure(placeholder: String, delegate : UITextFieldDelegate) {
        textField.placeholder = placeholder
        textField.accessibilityLabel = placeholder
        textField.delegate = delegate

    }

and amend the view controller likewise (wherever you call configure):

    cell!.configure("...", delegate:self)

END EDIT

I would also make activeTextField fully optional (not implicitly unwrapped), since it is entirely possible that it will be nil (if, for example, save is tapped before any textField has been edited). You should then use if let to unwrap the optional in the saveTapped method.

Upvotes: 1

Related Questions