Unable to find specific subclass of NSManagedObject

MsrButterfly picture MsrButterfly · Aug 1, 2014 · Viewed 38k times · Source

I'm working on developing an app with Core Data. When I created an instance using:

let entity = NSEntityDescription.entityForName("User", inManagedObjectContext: appDelegate.managedObjectContext)
let user = User(entity: entity, insertIntoManagedObjectContext: appDelegate.managedObjectContext)

I got a warning in log:

CoreData: warning: Unable to load class named 'User' for entity 'User'.  Class not found, using default NSManagedObject instead.

How could I fix it?

And another question, how can I define an instance method in NSManagedObject subclass?

Edit:

I have specified class of the entity as in the following screenshot:

enter image description here

Answer

Martin R picture Martin R · Aug 1, 2014

Update for Xcode 7 (final): Prepending the module name to the class (as in Xcode 6 and early beta releases of Xcode 7) is no longer necessary. The Apple documentation Implementing Core Data Managed Object Subclasses has been updated accordingly.

The Data Model inspector has now two fields "Class" and "Module" for an entity:

enter image description here

When you create a Swift managed object subclass for the entity, the "Module" field is set to "Current Product Module", and with this setting creating instances works both in the main application and in unit tests. The managed object subclass must not be marked with @objc(classname) (this was observed in https://stackoverflow.com/a/31288029/1187415).

Alternatively, you can empty the "Module" field (it will show "None") and mark the managed object subclasses with @objc(classname) (this was observed in https://stackoverflow.com/a/31287260/1187415).


Remark: This answer was originally written for Xcode 6. There were some changes in the various Xcode 7 beta releases with respect to this problem. Since it is an accepted answer with many upvotes and links to it, I have tried to summarize the situation for the current Xcode 7 final version.

I did both my own "research" and read all the answers to both this question and the similar question CoreData: warning: Unable to load class named. So attribution goes to all of them, even if I don't list them specifically!


Previous answer for Xcode 6:

As documented in Implementing Core Data Managed Object Subclasses, you have to prefix the entities class name in the Class field in the model entity inspector with the name of your module, for example "MyFirstSwiftApp.User".