What is the best way to stop an attempt at saving a CoreData Object if the user is missing input fields

I’m trying to make sure my users can’t accidentally make CoreData flip out when saving a new object. Say I need to confirm that a user entered their name and essentially the textfield isn’t empty.

What I planned to do here, is check whether it was empty and if so pop up an alert “Missing Data” or something and halt the save process. But my idea isn’t quite, working, but I wanted the tidiest neatest way to do it. Taking this as example of my save method.

@IBAction func done() {
    let hudView = HudView.hud(inView: navigationController!.view, animated: true)

    let location: Location
    if let temp = locationToEdit {
      hudView.text = "Updated"
      location = temp
    } else {
      hudView.text = "Tagged"
      location = Location(context: managedObjectContext)
      location.photoID = nil

   guard let text = descriptionLabel.text, !text.isEmpty else {
    // raise my alert here

do {
      try managedObjectContext.save()
      afterDelay(0.6) {
        self.dismiss(animated: true, completion: nil)
    } catch {

I expected my guard clause to exit the whole done() method. But I’m not sure it did here…

I have this happening in the simulator though. My alert is raised, and I click “Ok”. I then click cancel to go back to the main screen and see a blank row inserted into my table. If I close the simulator and re run it the row isn’t there.

But I think you can see the general gist of what I’m trying to do here, just wondered how people thought this was best achieved? :slight_smile:

Put the guard block first. (That’s actually a pretty good rule in general.)

As you have it now, this line:

location = Location(context: managedObjectContext)

creates the new row in core data before you check the input. That’s why you get a blank row. It doesn’t get saved, so it’s not there when you go back.

If you check the input first in the guard, you can exit without having done anything to the data.

1 Like