19
votes

What is the best way to add custom methods to my core data generated classes?

For example, say I have a "Person" entity with properties "firstname" and "lastname". I wish to add a "fullname" method, which returns a concatenation of the firstname and lastname properties.

I could add the method to the generated .h and .m files, but this would be difficult to maintain during development when my entities may still change. Recreating the .h and .m file would overwrite these changes. Another idea is to subclass the generated class and add the methods there.

Is there a better way?

3

3 Answers

40
votes

I find that the best way to add custom methods that aren't directly tied to data properties is to use a category. This generally works best if you create your Core Data entities as their own subclasses of NSManagedObject in the data modeler, but it can work without that as well. This way all the machine generated code can stay in the main .h and .m files, and all your custom code goes in the .h and .m for your category on that class.

1
votes

I'd recommend adding these methods to your custom NSManagedObject subclass. If you're worried about maintaining accessors as your data model changes, while preserving your custom methods, I'd suggest looking to "Wolf" Rentzsch's mogenerator. Many people swear by this tool for just this purpose.

0
votes

You create your own subclass of NSManagedObject for the entities.

Better explained in the NSManagedObject documentation