Monday, 22 September 2014

Working With Core Data in Swift

In general, working with Core Data is similar to how you would do it in Objective-C. You use the Data Model Design tool to create your managed object model. When creating your project, if you selected "Use Core Data", Xcode will automatically create the functions to create and get the NSPersistentStoreCoordinator, NSManagedObjectContext, and set up your Apps document directory, and even provides a function to save your context.

After you create your entities in your managed object model, you can automatically generate the Swift class files for your entities by selecting your data model file (.xcdatamodeld), and selecting Editor->Create NSManagedObject subclass.

One gotcha is that in Swift all of your classes are namespaced to the module they are compiled in (typically this is your project). For example, if you have a project called MyProject and you have a class in it called MyModel, in order to refer to the class in your managed object model, you will need to use MyProject.MyModel.

This means that after you have created your entity models in your managed object model and generated your Swift classes for your entities, you will need to go back and prefix "MyProject." to the class name in the Class field in the Data Model inspector panel for each of your entities.

Otherwise you will get the following error:
CoreData: warning: Unable to load class named 'MyModel' for entity 'MyModel'. Class not found, using default NSManagedObject instead.
This is clearly stated in Using Swift with Cocoa and Objective-C. But, I would imagine that if I generated the Swift classes from the model file, I would have this automatically set for me. The fact that I have to set this manually seems like a short fall in Xcode. Hopefully Apple will fix this soon.