How to Create Managedobjectcontext Using Swift 3 in Xcode 8

How to create managedObjectContext using Swift 3 in Xcode 8?

In Swift3, you can access the managedObjectContext via the viewContext as

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

This option is available if Core data was enabled when creating the project. However, for existing project that you want to include core data, go through the normal process of adding the core data and add the following code which will allow you to get the

lazy var persistentContainer: NSPersistentContainer = {

let container = NSPersistentContainer(name: "you_model_file_name")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error {

fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()

You will need to import the CoreData.

Note: For Swift3, the ManagedObject Subclass are generated automatically.
See more from WWDC 2016

Swift 3/XCode 8 NSManagedObjectContext.fetch error

Try this:

do {
objects = try managedObjectContext.fetch(fetchRequest) as! [YourEntityName]
} catch {
print(error)
}

How to create and store managed objects containing the data using Swift 3.0 in Xcode 8.2

This is how you configure the Core Data codegen in Xcode 8:
Example entity details

You have 3 options:

  • Manual/none
  • Class Definition
  • Category/Extension

I think they are pretty self-explanatory. Anyway what you probably want here is Class Definition.

Setting managedObjectContext in AppDelegate

You can access the managed object context all over the app using the following line of code.

let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

So you can remove the following line.

controller.managedObjectContext = self.managedObjectContext


Related Topics



Leave a reply



Submit