无法更新核心数据对象

时间:2017-04-05 11:32:42

标签: ios swift xcode core-data insert

我能够插入,查找,删除核心数据对象但无法更新现有的核心数据对象。 StudentTable是实体。 id,rollnumber,classnumber,classid,classname是属性。

我创建了 NSEntityDescription NSFetchRequest NSPredicate 但仍未将数据更新到现有核心数据对象。 按下更新按钮时整个对象被删除,我不知道如何。

更新按钮操作代码

@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)

    }
}

任何建议都会表示赞赏,谢谢。

使用xcode 8.2,swift 3

0 个答案:

没有答案