swift - NSMangedObjectContext不刷新数据

时间:2015-11-25 23:52:58

标签: ios swift cocoa-touch core-data

我有两个视图控制器,第一个用于显示存储在CoreData中的对象列表,第二个用于创建新对象。

创建新对象后,我返回到对象列表,但新创建的对象不存在。重新启动应用程序后,将显示新对象。这是我的代码:

ListOfProjectsViewController:

var projects:[ProjectItem] = []

lazy var managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

    override func viewDidAppear(animated: Bool) {
        loadProjects()
    }

    func loadProjects() {

        do {
            let results = try managedObjectContext.executeFetchRequest(fetchRequest)
            projects = results as! [ProjectItem]

            tableView.reloadData()
        } catch let error as NSError {
            print("Could not fetch \(error), \(error.userInfo)")
        }

    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "CreateNewProjectSegue" {
            let vc = segue.destinationViewController as! CreateNewProjectViewController
            vc.project = NSEntityDescription.insertNewObjectForEntityForName("ProjectItem", inManagedObjectContext: managedObjectContext) as? ProjectItem
        }
    }

CreateNewProject:

let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var project:ProjectItem?

@IBAction func saveAndCloseBtnPressed(sender: AnyObject) {
        project?.title = projectTitleField.text
        project?.number = projectNmField.text
        project?.comments = projectCommentsTextView.text

        try! project?.managedObjectContext?.save()

        do {
            try self.managedObjectContext.save()
        } catch {
            fatalError("Failure to save context: \(error)")
        }

        self.navigationController?.popViewControllerAnimated(true)

    }

我做错了什么?

1 个答案:

答案 0 :(得分:1)

managedObjectContext.executeFetchRequest(fetchRequest)返回一个静态数组,因此当基础数据发生变化时它不会更新。

您应该使用NSFetchedResultsController代替,然后您可以在更改内容时收到更新通知。