我正在尝试将一些文本从UITextField保存到xcode 7中的CoreData,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!")
}
}
但是,它将信息存储为nil,当我尝试使用(titleName.text!,forKey:...)时(例如)它给我一个错误 - 尝试解包和可选的nil -
有谁知道修复?提前谢谢你:)
答案 0 :(得分:1)
您可以使用nil合并运算符,例如:
let text = titleName.text ?? "n/a"
newIdea.setValue(text, forKey: "title")