Smarter NSEntityDescription declaration

A common situation in software development is that an application will evolve over time often resulting in some refactoring work to your existing code base. For the most part xCode's built in refactoring tool works well however an area that it fails on is NSEntityDescription declarations.


If I have a CoreData table called: "Person". Now as my application evolves I decide that "Person" is no longer accurate to describe what this table contains and decide to change it "Player". I'd pop on the refactoring tool, change the name and xCode would take care of the rest.

However if my NSEntityDescription declarations looked like this:

[NSEntityDescription insertNewObjectForEntityForName@"Person" inManagedObjectContext:self.managedObjectContext];

The refactoring tool would skip past it without changing the string "Person" to "Player" and when this statement is executed my application would crash. I could search for the word "Person" and run through my code and change it to "Player" but then I risk missing one. A much better approach is to get the refactoring tool to do it for us:

[NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Person class]) inManagedObjectContext:self.managedObjectContext];

Here we use NSStringFromClass([Person class]) to create the needed string but we keep the connection with the actual class. So when we refactored this is updated to NSStringFromClass([Player class]) and we get to move more quickly onto adding that super cool new feature