managedObjectContext in Swift 3

前端 未结 4 972
故里飘歌
故里飘歌 2021-02-19 23:30

I want to work through this example code in which Swift and CoreData is used to create a table. However, using Swift 3 I fail to get it to work. Most importantly, I cannot prope

4条回答
  •  礼貌的吻别
    2021-02-19 23:59

    Swift 3 in macOS

    let appDelegate = NSApplication.shared().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    

    The error you provided says 'AppDelegate' has no member 'managedContext' instead of 'AppDelegate' has no member 'managedObjectContext', which would lead me to assume you just need to fix your syntax.

    Swift 3 in iOS 10

    Core Data needs at least 3 things to work:

    1. A managed object model
    2. A persistent store coordinator
    3. And a managed object context

    Put those three things together and you get the Core Data Stack.

    When iOS 10 came out, a new object was introduced called the NSPersistentContainer which encapsulates the core data stack.

    How to create the container object is answered here.

    managedObjectContext is now a property called viewContext, accessed via:

    let delegate = UIApplication.shared.delegate as! AppDelegate
    let managedObjectContext = delegate.persistentContainer.viewContext
    

    A helpful article is What's New in Core Data, but if that reading seems a little too heavy, this WWDC video does a great job of explaining this topic.

提交回复
热议问题