简体   繁体   中英

How to save UITextField to Core Data in swift 2?

I am trying to save some text from UITextField to CoreData in xcode 7, swift 2.0

  @IBOutlet weak var titleName: UITextField!
@IBOutlet weak var problemDescription: UITextField!
@IBOutlet weak var targetMarket: UITextField!

//Save information to core data
@IBAction func saveInformation(sender: AnyObject)  {
    print("Attempting to save!")
    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext
    let newIdea = NSEntityDescription.insertNewObjectForEntityForName("SaveIdea", inManagedObjectContext: context)
    print("\(titleName) is cool")
    newIdea.setValue("\(titleName)", forKey: "title")
    newIdea.setValue("\(problemDescription)", forKey: "targetMarket")
    newIdea.setValue("\(targetMarket)", forKey: "problemSolved")
    do{
        try context.save()
        print("Save Success!")
    }catch {
        print("Error!")
    }

}

However, it stores the information as nil, and when I try and use (titleName.text!, forKey:...) (eg) its gives me an error - trying to unrap and optional that is nil -

Does anyone know the fix? Thank you in advance :)

You could use the nil coalescing operator, for example:

let text = titleName.text ?? "n/a" 
newIdea.setValue(text, forKey: "title")

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