Dealing with Core Data Duplicate Class Errors
Many people learning Core Data take the following steps when creating their first Core Data app:
- Create a new Xcode project that uses Core Data.
- Create Code Data entities and relationships in Xcode’s data model editor.
- Create subclasses for their entities by choosing Editor > Create NSManagedObject Subclass in Xcode.
They build the project and get the following build error:
Invalid redeclaration of Entity
Where Entity
is the name of a Core Data entity.
What Causes the Error?
When you create a new Xcode project that uses Core Data, Xcode is set to automatically create NSManagedObject subclasses for your Core Data entities. Xcode creates the subclasses when you build the project.
The source code files Xcode creates are in the project’s derived data location. You can’t see the files in the left side of the project window like the other source code files in your project. You’re not meant to access and edit the source code files Xcode creates for your Core Data entities. The point of Xcode creating the files is to automatically update the files when you make changes to the data model.
If you create NSManagedObject subclasses from Xcode’s Editor menu, you wind up with two files for each subclass: the one Xcode automatically generates and the one you create.
When you have two classes with the same name, Xcode gives you the “Invalid redeclaration” error, and your project won’t build.
How do You Fix the Error?
There are two ways to fix the error. The first way is to remove the class files you added and let Xcode generate the classes for you.
The second way is to tell Xcode not to generate class files for your Core Data entities by choosing Manual/None from the Codegen menu in Xcode’s data model inspector. Choose View > Inspectors > Data Model in Xcode to access the data model inspector. Read the following article for screenshots and more details on Core Data class generation options: