Function not saving string on textfield to core data

My function below when called is not saving whatever is on the textfield to core data. When appearing in the debug area what appears is “”. This code when used in the view did load function it does work but when I call it it does not work.This code saves a image on the imageview perfectly. I dont know why it is working in one area and not in the other.

       var playName = UITextField()
  func saver() {
    let vex = drawPlace.screenshot().pngData()
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
    let managedContext = appDelegate.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "Users", in: managedContext)!
    let item = NSManagedObject(entity: entity, insertInto: managedContext)
    let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")

    
    if let data = vex{
        item.setValue(data, forKey: "image")
    }

    
 item.setValue(playName.text, forKey: "username")
    
    do {
        let result = try? managedContext.fetch(fetch) as? [Users]
        print("Queen",result?.count)
        try? managedContext.save()
        

        }
    catch {
        print("Could not save")
    }
    
}

Is playName properly bound? If you set a breakpoint in the method, is there a value to text?

I would keep a guard statement at the top of the method, since it seems like a key part of your code. If it’s coming in empty from GUI, it probably shouldn’t save, right?

You mentioned it works on viewDidLoad, where else are you calling it? Is it from an action? Is the UITextField bound then?

I updated my code above. Less stuff in it but the same problem is happening. I can save my imageview but the string is not saving. The textfield when saved has nothing in it. PlayName is a UITextfield positioned by code in view did load. . This function is a action. Can you show me where I would part the guard part.

This is a link to my project. Code is just not saving the text. Thanks.

I didn’t see a link, but it may not be necessary. Let me explain, the question is: is the UITextField.text property nil or empty? You can check on it with a guard, if it is, then there’s the problem to begin with.

@IBAction func buttonPressed(_ sender: Any) {
    guard let text = playName.text, text.count > 0 else { return }
    print("Text = \(text)")
}

Another quick way to do it, is to setup a breakpoint on the save and inspect the value.

Just added that guard code seems to have no effect. This is the link to my project Dropbox - CoreDataDemo-master.zip - Simplify your life.

When setting the breakpoint, what did you see for playName.text?

this is a photo of my debugg area. 56%20PM

What happens if you step over (advance the instruction pointer)? Does it return on the method or proceed?

in submitAction(), you start off by setting playName.text = “”. This then breaks at the guard point since the length is 0.

This is the photo of what I think you are asking me to do. 41%20AM This is while I run the app with the breakpoint.

That’s exactly it! Except none of the local constants or variables are showing. I’ll download the source over the weekend and will take a look.

Side note: Github is best for sharing code, I can upload/commit my fixes and you can track them with annotations.

I made these changes to your code and it worked.

@objc func submitAction() {

    if let textEntered = self.playName.text {
        if textEntered.isEmpty != true {
            saver(text: textEntered)
                print("Saves the textfield text")
        } else { print("Text Field was empty nothing to save.")}
    } else {  print("The text field was nil")
         }
    
    playName.resignFirstResponder()
    
    clearAction()
   
    
}

func saver(text: String) {

    let vex = drawPlace.screenshot().pngData()
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
    let managedContext = appDelegate.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "Users", in: managedContext)!
    let item = NSManagedObject(entity: entity, insertInto: managedContext)
    let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")

    
    if let data = vex{
        item.setValue(data, forKey: "image")
        print(data)
    }

    
 item.setValue(text, forKey: "username")
    
    do {
        let result = try? managedContext.fetch(fetch) as? [Users]
        print("Queen",result?.count)
        try? managedContext.save()
        
           print("Text = \(text)")

        }
    catch {
        print("Could not save")
    }
    
}

}

1 Like

Thats It it worked. Your the man or woman whatever your sex is!

Unwrap the playerName.text as playName.text! when setting the value

This topic was automatically closed after 166 days. New replies are no longer allowed.