Kesong Xie
Kesong Xie

Reputation: 1396

Core Data - The correct way to subclass NSManagedObject in objective-c project Xcode 8

I just get started learning how to use Core Data today and encountered an issue when I have to subclass from NSManagedObjectin my objective-c project. I'm following the Stanford iOS 7 class(I come from Swift background and want to learn more about objective-c) Stanford University Developing iOS 7 Apps: Lecture 13 - Core Data and Table View Here is what I've done so far:

First

Create my CoreDataModel.xcdatamodeld file, and configure my entities like this

enter image description here

Next

With the CoreDataModel.xcdatamodeld file highlighted, I go to the Editor and try to create NSManagedObject subclass

enter image description here

Four Swift files were created inclduing an empty bridging header file MyProject-Bridging-Header.h.

enter image description here

I have a many compiler errors: enter image description here

I'm confused about why the xcode will generate Swift files for me instead of objective-c one since I have already configured using objective-c as my language.

How can I configure my header file to make objective-c recognize my Swift files or is there a way to create objective-c subclass file instead, such as .m and .h file?

The redeclaration error may come from the the codegen issue Xcode automatic subclass generation

My drived data have the following files enter image description here

Any suggestion is appreciated.

Upvotes: 10

Views: 4188

Answers (2)

Arpit Dongre
Arpit Dongre

Reputation: 1713

This Answer here already covered how to generate Swift files. Mine covers other queries in question.

Xcode now supports automatic generation of NSManagedObject subclasses in the modeling tool. 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.

For more refer this Apple Documentation.

Solution for Invalid redeclaration of NSManagedObject:

For XCode 8.1, before you create NSManagedObject through Editor, select your Entity, go to Data Model Inspector and under Codegen select 'Manual/None' like this:

And then create NSManagedObject subclass.

In case you have already created NSManagedObject subclass, do the following steps:

  1. Go to your current .xcdatamodeld, set all Entities Codegen to 'Manual/None'.
  2. Save the project, delete Derived Data.
  3. Clean & build the project.

It should work.

Upvotes: 9

Łukasz Przytuła
Łukasz Przytuła

Reputation: 575

When you select your model in Project navigator, in File inspector you have an option to select the language in which code will be generated:

Changing language of generated model

Upvotes: 15

Related Questions