Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom methods to core data classes

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?

like image 636
chris Avatar asked Dec 24 '09 10:12

chris


2 Answers

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.

like image 100
Shawn Craver Avatar answered Nov 04 '22 05:11

Shawn Craver


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.

like image 31
Brad Larson Avatar answered Nov 04 '22 04:11

Brad Larson