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:
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
Xmppframework - Implement Group Chat (Muc)
How to Make Uitextview Detect Links for Website, Mail and Phone Number
Is Nstimer Expected to Fire When App Is Backgrounded
Getting Local Notifications to Show While App Is in Foreground Swift 3
Swift 3 - How to Verify Class Type of Object
Ios: Sample Code for Simultaneous Record and Playback
Swift Compiler Shows Expected Declaration Error
How to Get a List of Points from a Uibezierpath
How to Implement the Hashable Protocol in Swift for an Int Array (A Custom String Struct)
Check If a Uialertview Is Showing
How to Apply Uiappearance Proxy Properties to Uilabel
Use Multiple Font Colors in a Single Label
Record and Play Audio Simultaneously
Getting the Word Touched in a Uilabel/Uitextview
How to Combine React Native with Socket.Io