Question

I'd like to place some custom methods directly into each NSManagedObject. Think, "calculated fields": these methods provide read-only calculated values based upon persistent values on the Entity - which is identical to this question.

I'm using the Xcode New File... Wizard to create NSManagedObject subclasses for each of my Entities. I'm trying to benefit from the system auto-creating the accessors for me. For example:

Core Data Entity: "Site"

@interface Site : NSManagedObject

As I continue to add new Attributes to my Entities, I'm replacing their corresponding NSManagedObjects by using the Wizard. When each file is replaced, my custom methods are lost.

Should I create my custom methods elsewhere so that I can continue to leverage the Wizard? Or, should I keep the methods on the NSManagedObject and add Accessors for new Attributes manually? Is there another approach?

Was it helpful?

Solution

Create a category on your NSManagedObject subclass:

  • In the "New File ..." dialog, choose "Objective-C category".
  • Create a category "CustomMethods" on "Site".
  • Xcode will create files Site+CustomMethods.h, declaring the @interface Site (CustomMethods), and Site+CustomMethods.m for the corresponding implementation.
  • Add your custom methods to the category.

These files will not be overwritten when you recreate Site.m and Site.h in Xcode.

All category methods can be used as if they had been declared in the class itself. The only thing you can not do in a category is add new instance variables.

OTHER TIPS

Once I have used the wizard to create the initial managed objects, I generally change them manually.

Another way of doing this is to create subclasses of the wizard generated class files and use these. When they are regenerated, all of your custom code is in the subclass, as opposed to the overwritten class file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top