0
votes

I have a simple entity in my core data stack (called Diary). This entity has one attribute (name)

I generated the NSManagedObject subclass using the Editor. I also made sure that the class name follows appName.DiaryEntry format

xcode 7 removes the "." and gives me a class with the name: appNameDiaryEntry

Here's the code i am using

let diaryEntry : DiaryDiaryEntry

diaryEntry = NSEntityDescription.insertNewObjectForEntityForName("DiaryDiaryEntry", inManagedObjectContext: dataStoreController.managedObjectContext!) as DiaryDiaryEntry

In the code above, DiaryDiaryEntry is the NSManagedObject subclass that was created from the coredata model.

I get an error saying that

'NSManagedObject' is not convertible to 'DiaryDiaryEntry'

If i force a downcast using as!, it works but i get an error during run time (because the value was nil and was force unpacking?)

Any ideas how to fix this? Thanks, Karthik

3

3 Answers

0
votes

You certainly have to downcast with as! however there's something else that is obviously going wrong when NSEntityDescription.insertNewObjectForEntityForName(...) is returning nil. You should check if your entity name is correct (has to be the same name as the one specified for the entity in the data model). You might want to have a look at the data model inspector when opening the data model and selecting the desired entity: you have to specify the name of your class under Class and select Current Project Module under Module.

0
votes

For your case, I recommend using the same entity name and class name. (More details here.) Thus, you should eliminate the (clumsy) "DiaryDiaryEntry", and replace it with "DiaryEntry".

0
votes

First, since insert.. returns AnyObject, you need to cast it. There are several ways to do it with as! having the highest risk of a runtime crash.

You could also set it up as a guard with something like:

let entity = NSEntityDescription.insertNewObjectForEntityForName("DiaryDiaryEntry", inManagedObjectContext: dataStoreController.managedObjectContext!) as? DiaryDiaryEntry else { fatalError("Failed to load subclass") }

Which will still give you a runtime error the way I wrote it but it allows you to control the event.

As for getting a nil back, that indicates you have a type in the entity name either in your model or in that line of code. That line of code should never return nil. I suspect your actual entity name is DiaryEntry.

As Mundi pointed out, your class name is a bit repetitive. While he likes to keep the class and model name the same, I prefer to suffix my class names which would make yours DiaryEntryMO which I find to be very easy to consume when maintaining code.