cannyboy
cannyboy

Reputation: 24426

Why are some entities NSManagedObjects and some named after their class?

I've noticed that in my Core Data data model, some entities are (in the top-left panel) have a class of 'NSManagedObject' and some are named after a class (Person, Company etc). There doesn't seem to be any logic in whether the entity has a class of NSManagedObject of Person etc. And my code seems to work ok. So I'm wondering why there is the disparity?

EDIT

Thanks for Benedict Cohen for making things a bit clearer. This is my current code:

Person *per = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext];
[per setName:@"Steve Jobs"];

..This works whether a custom class is explicitly mentioned in the Data Model or not. But I would still need the custom class. Am I doing this wrong? I wonder if I can simplify my code. The custom classes were created by selecting the entities and going to 'New File - Managed Object Class'.. but I think links may have broken when I changed them.

Upvotes: 0

Views: 165

Answers (1)

Benedict Cohen
Benedict Cohen

Reputation: 11920

It's good practice to create a class for each entity, but it is not required. By creating a class for an entity it makes it possible to use properties instead of setValue:forKey: eg:

person.name = @"Harry Hippy"; //this is good
[person setValue:@"Harry Hippy" forKey:@"naem"]; //this is bad. The compiler won't notice the typo and will result in a run-time error

You'll have to create a class as soon as Person needs to do more than store data.

Upvotes: 2

Related Questions