I'm trying to create a subclass of NSManagedObject in swift. I have created two entities called Pages and Book in the model editor and generated their class files. Here are the two classes:
@objc(Pages)
class Pages: NSManagedObject {
@NSManaged var pageNo: NSNumber
}
@objc(Book)
class Book: NSManagedObject {
@NSManaged var pageCount: NSNumber
@NSManaged var title: String
@NSManaged var fetchLastPage: [Pages]
}
As a test to create an Instance of Pages I wrote this code in ViewDidLoad which failed because it couldn't find the entity in the model:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
var pages = NSEntityDescription.insertNewObjectForEntityForName("StoreTest.Pages", inManagedObjectContext: managedContext)
'StoreTest' is the name of my application which is also set in the model editor for the two entities. To see what's going on I added this code before creating the instance:
var pagesEntity = NSEntityDescription.entityForName("StoreTest.Pages", inManagedObjectContext: managedContext)
println("pagesEntity = \(pagesEntity)")
var ents = managedContext.persistentStoreCoordinator!.managedObjectModel.entities
println("entities = \(ents)")
The NSEntityDescription.entityForName call returns nil, but the call to managedObjectModel.entities returns the two entities.
I made sure there's no spelling problem. Also, the managedObject is not nil. The target of my data model file is correctly set to my app module.
I'm using xCode 6.4.
Thanks for your help!
Remove the additional StoreTest.
from the entity name, you don't need it there and the dot is likely causing some issue with the lookup.
It might actually just be that you are confused about what the entity name is, it's set in the model and then you set the class name (usually to the same as the entity name).