Xcode 8: Core Data Class Generation
March 1st, 2017
Xcode 8 adds support for automatically creating classes for your Core Data entities. If you look at Xcode’s data model inspector, you will see a Codegen menu.
The Codegen menu has the following items:
- Manual/None, which means Xcode does not generate code files for the entity. This is the same behavior that previous versions of Xcode had. You must create the classes for your entities by choosing Editor > Create NSManagedObject Subclass in Xcode.
- Class Definition, which means Xcode generates the entity’s class files for you. Xcode does the equivalent of you choosing Editor > Create NSManagedObject Subclass. Class Definition is the default option for new projects.
- Category/Extension, which means Xcode creates an Objective-C category or Swift class extension for the entity.
If you choose Class Definition or Category/Extension for one of your entities, make sure you don’t manually create a
NSManagedObject subclass for that entity. Manually creating the subclass creates duplicate class files, and your project won’t build. Remove the manually created subclass files from the project if you have duplicate files.
Where Are the Files?
If you choose Class Definition or Category/Extension from the Codegen menu, you’ll notice there are no files for the
NSManagedObject subclasses in your project. Where are the files?
Xcode creates the files when you build the project. The files are in your project’s derived data location. Read my Changing Xcode’s Build Location post for more information on the derived data location. You’re not meant to access and edit the Core Data class files Xcode creates. The point of Xcode creating the class files is to automatically update the files when you make changes to the data model.
What do you do if you want to add methods to your
NSManagedObject subclasses? Create a new file for your methods. Add either a Swift class extension or an Objective-C category.
Which Codegen Option Should You Use?
In most cases you should use either the manual or class definition codegen options. The advantage of the class definition codegen option is you don’t have to worry about forgetting to change your classes when you change your data model. Xcode keeps the class and data model in sync. The advantage of manually creating your Core Data class files is you can access them in the project window and edit them.