JAHelia JAHelia - 22 days ago 5
Swift Question

Swift: entityForName: could not locate an entity named xxx in this model

I created a test project to fetch data from

http://api.androidhive.info/contacts/
everything works fine, but when I try to save the data returned by the web service to a data model entity named
ContactDB
by

let rowDB = NSEntityDescription.insertNewObjectForEntityForName(NSStringFromClass(ContactDB.self), inManagedObjectContext: moc) as! ContactDB
,

I get this runtime crash:
+entityForName: could not locate an entity named 'TestAlamofire5.ContactDB' in this model


I have tried every possible solution mentioned in all related posts in SO:

changed the entity name

prefixed the NSManagedOBject subclass with @objc attribute

deleted the entity and created a new one

deleted the whole data model and created a new one with a new entity

cleaned the project or even created a new project

but to no avail ...

what am i doing wrong to get this crash ?

p.s. the test project can be downloaded here

Answer

The easiest - and expected - way is to pass the literal name of the entity.

let rowDB = NSEntityDescription.insertNewObjectForEntityForName("ContactDB", inManagedObjectContext: moc) as! ContactDB