Coredata - 更新信息

时间:2016-11-25 12:31:16

标签: swift core-data swift3 xcode8

我有两个viewcontrollers。 VC1是家庭视图控制器。 在VC2中,我有文本字段,以便用户输入结果和保存数据的保存按钮。 奇怪的是,当我保存时,我有一个fetchrequest来显示新数据但是...发生的事情是向我显示旧数据。

但如果我去VC1,那里会有新数据。

这是我的代码(VC2):

@IBOutlet var designLabel: UITextField!
@IBOutlet var localLabel: UITextField!
@IBOutlet var typeLabel: UITextField!


override func viewDidLoad() {
    super.viewDidLoad()

    let fetchRequest:NSFetchRequest<Arm> = Land.fetchRequest()
    fetchRequest.predicate = NSPredicate(format: "id = %@",  "\(choosenArmID!)")

    do{
        let searchResults = try DatabaseController.getContext().fetch(fetchRequest)

        for result in searchResults as [Arm]{
               //to get results in coredata and put them in the text fields: for edition
                self.title = result.designation
                designLabel.text = result.designation
                localLabel.text = result.local
                typeLabel.text = result.type
        }
    }
    catch{
        print("Error: \(error)")
    }

}

保存按钮我有:

@IBAction func saveButton(_ sender: UIBarButtonItem) {

    let app = UIApplication.shared.delegate as! AppDelegate
    let context = app.persistentContainer.viewContext
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Arm")
    request.predicate = NSPredicate(format: "id = %@",  "\(choosenArmID!)")        
    do {
        let results = try context.fetch(request)

        if results.count > 0 {

            for result in results as! [NSManagedObject] {

                    result.setValue(designLabel.text, forKey: "designation")
                    result.setValue(typeLabel.text, forKey: "type")
                    result.setValue(localLabel.text, forKey: "local")

                do {
                    try context.save()
                    print("context saved") //I get into this
                } catch {
                    print("Error updating")
                }   
            }
        }
    } catch {

        print ("Error")
    }


 //I do another fetchrequest to show new results

    let fetchRequest:NSFetchRequest<Arm> = Arm.fetchRequest()
    fetchRequest.predicate = NSPredicate(format: "id = %@",  "\(choosenArmID!)")

    do{
        let searchResults = try DatabaseController.getContext().fetch(fetchRequest)

        for result in searchResults as [Arm]{
            print("New saved Results: ")
            print("title: \(result.designation!)")
            print("local: \(result.local!)")
            print("type: \(result.type!)")
        }
    }
    catch{
        print("Error: \(error)")
    }

}

现在在新的结果中,我预计会有新的保存结果,但我会得到旧结果,即使新结果已保存! 你能帮帮我吗?

0 个答案:

没有答案