Failed to update the main data object
I can insert, find, delete the main data object, but could not update the existing main data object. StudentTable is an entity. id, rollnumber, classnumber, classid, classname are attributes.
I created NSEntityDescription, NSFetchRequest, NSPredicate, but still the data is not updated to the existing main data object. The entire object gets deleted when the refresh button is clicked, which I have no idea how to do.
Refresh button action code
@IBAction func update(_ sender: UIButton) {
if(id.text != nil)
{
let entityDescription = NSEntityDescription.entity(forEntityName: "StudentTable", in: managedObjectContext)
let request: NSFetchRequest<StudentTable> = StudentTable.fetchRequest()
request.entity = entityDescription
let pred = NSPredicate(format: "(id = %@)", id.text!)
request.predicate = pred
let studenttable = StudentTable(entity: entityDescription!, insertInto: managedObjectContext)
do {
var results =
try managedObjectContext.fetch(request as! NSFetchRequest<NSFetchRequestResult>)
if results.count > 0 {
let match = results[0] as! NSManagedObject
match.setValue(String(describing: id.text), forKey: "id")
match.setValue(Int(rollnumber.text!), forKey: "rollnumber")
match.setValue(Int(classnumber.text!), forKey: "classnumber")
match.setValue(Int(classid.text!), forKey: "classid")
match.setValue(String(describing: classname.text!), forKey: "classname")
do {
try managedObjectContext.save()
beacondataobject.append(studenttable)
let alert = UIAlertController(title: "Alert", message: "updated data", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
} else {
//noting found
let alert = UIAlertController(title: "Alert", message: "No data found", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Search Again", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
} catch let error {
print("error %@", error)
}
}
else{
let alert = UIAlertController(title: "Alert", message: "Enter id to search", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Try Again", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
Any suggestion would be appreciated, thanks.
using xcode 8.2, swift 3
+3
source to share
No one has answered this question yet
See similar questions:
or similar: