iOS Quick Tip – Core Data and “unrecognized selector sent to instance 0xsomething”

While experimenting with Core Data, I ran into a little issue with the always annoying ‘unrecognized selector’ exception.
I had created my Core Data model, along with my NSManagedObjectContext classes, and I was trying to use them like this:

Foo* foo = [[Foo alloc] init]; = @"This line will crash!";

… which of course results in the aforementioned exception.

This is what happens when you don’t read the documentation. It quite clearly states that you pretty much have to use NSEntityDescription’s insertNewObjectForEntityForName:inManagedObjectContext method to create your objects.

And sure enough, if you create your objects like this instead:

Foo* foo = [NSEntityDescription insertNewObjectForEntityForName:@"Foo" inManagedObjectContext:context];
foo.summary = @"This is a bug";

it works as expected.

That said, making a class called ‘NSEntityDescription’ responsible for creating objects and adding them to a context seems like a somewhat dubious design decision.