我正在研究一个快速的3教程并且核心数据存在问题。 在运行代码时我能够保存我的数据,我想,但是当我想将它加载到我的控件中时,我得到一个错误。 image of the app
这是我的代码:
lazy var managedObjectContext: NSManagedObjectContext? = {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
return context
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func speichernPressed(_ sender: UIButton) {
writeData()
}
@IBAction func ladenPressed(_ sender: UIButton) {
loadData()
}
func writeData() {
let kontakt = NSEntityDescription.insertNewObject(forEntityName: "Kontakte", into: self.managedObjectContext!) as! Kontakte
kontakt.vorname = vornameTextField.text!
kontakt.name = nameTextField.text!
kontakt.plz = plzTextField.text
kontakt.ort = ortTextField.text!
kontakt.strasse = straßeTextField.text!
do{
try managedObjectContext?.save()
} catch {
}
showAlertViewWithTitle(title: "Hinweis", message: "Datensatz wurde gespeichert!")
vornameTextField.text = ""
nameTextField.text = ""
straßeTextField.text = ""
ortTextField.text = ""
plzTextField.text = ""
}
func loadData() {
let fetchRequest = NSFetchRequest<Kontakte>(entityName: "Kontakte")
let predicate = NSPredicate(format: "nameTextField contains %@", nameTextField.text!)
fetchRequest.predicate = predicate
var fetchResults: [Kontakte] = []
do {
try fetchResults = managedObjectContext!.fetch(fetchRequest)
if(fetchResults.count > 0) {
nameTextField.text = fetchResults[0].name
vornameTextField.text = fetchResults[0].vorname
straßeTextField.text = fetchResults[0].strasse
ortTextField.text = fetchResults[0].ort
plzTextField.text = fetchResults[0].plz
}else {
showAlertViewWithTitle(title: "Hinweis", message: "Datensatz nicht gefunden!")
}
}catch {
showAlertViewWithTitle(title: "Fehler", message: "Bei der Verarbeitung ist ein Fehler aufgetreten!")
}
}
func showAlertViewWithTitle(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Schliessen", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'unimplemented SQL generation for predicate : (nameTextField CONTAINS "Lebowski")'
我很感激任何帮助
答案 0 :(得分:0)
我通常做这样的事情
var contacts = [Kontakte]()
例如在viewDidLoad
中 let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let contactFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Kontakte")
do {
contacts = try managedContext.fetch(contactFetch) as! [Kontakte]
// loop results
for contact in contacts {
print(contact.vorname)
}
} catch {
fatalError("Failed to fetch contacts: \(error)")
}