Search code examples
iosswiftxcodecore-datansmanagedobject

Is it unnecessary to subclass NSManagedObject in Swift 3?


I know previously you would have to "Editor" > "Create NSManagedObject Subclass" in order to reference your Core Data's entity names in your classes. However I'm given several errors after creating these automatic subclasses.

My project runs fine without these subclass files, so does Swift 3 not require subclassing to reference entities anymore?


Solution

  • In Swift 3 you don't need to manually create subclasses for NSManagedObjects.

    By default they are created automatically. But if you want manually create files, set Codegen to Manual/None in Utilities area for your testCD.xcdatamodeld.

    From Apple's What's new in Core Data:

    Xcode automatic subclass generation

    Xcode now supports automatic generation of NSManagedObject subclasses in the modeling tool. In the entity inspector:

    • Manual/None is the default, and previous behavior; in this case you should implement your own subclass or use NSManagedObject.
    • Category/Extension generates a class extension in a file named like ClassName+CoreDataGeneratedProperties. You need to declare/implement the main class (if in Obj-C, via a header the extension can import named ClassName.h).
    • Class Definition generates subclass files named like ClassName+CoreDataClass as well as the files generated for Category/Extension.

    The generated files are placed in DerivedData and rebuilt on the first build after the model is saved. They are also indexed by Xcode, so command-clicking on references and fast-opening by filename works.