1

One of my core data subclasses has an NSSet of items. It is often (but not always, so no NSOrderedSet) useful to instead retrieve an ordered NSArray, so I added orderedItems to the class, which sorts them.

I then ran into performance issues so decided to try caching the orderedItems. My plan is to use an iVar, _cachedOrderedItems in the class, which I will return if it is not null.

The snag comes with my use of categories. I read some good advice about putting all of my custom code in a category so that I can re-generate the core data class if necessary and not lose all my customizations. One of those customizations is the orderedItems method.

It seems I can not declare an iVar in the category itself. And if I try to put it in the core data class instead, I can not access it in the category.

Do I need to move my custom code back into the core data class? Or am I missing something?

I have also heard about Mogenerator, and would consider learning to use this if it would help.

Ben Packard
  • 26,102
  • 25
  • 102
  • 183

3 Answers3

1

You can use associative references to add ivars to a class any time you can't modify the original class, including in categories. For a detailed example, see Faking instance variables in Objective-C categories with Associative References.

jatoben
  • 3,079
  • 15
  • 12
1

You own the class, so you can use a class continuation (discussed here) instead of a category. This allows you to add instance variables.

Community
  • 1
  • 1
jrturton
  • 118,105
  • 32
  • 252
  • 268
0

You should definitely use mogenerator. See for example http://importantshock.wordpress.com/2006/12/19/mogenerator-or-how-i-nearly-abandoned-core-data/.

You can make an Aggregate target in XCode, add a Run Script with the following:

mogenerator -m path/to/your/datamodel.xcdatamodeld/version.xcdatamodel --template-var arc=true -M /CoreData/Generated -H /CoreData

For every NSManagedObject you get a class and a subclass. When updating your datamodel, run the script again and the base class will be updated, preserving all the changes you made to the managed object subclass. Remove --template-var arc=true for none arc.

Jorn van Dijk
  • 1,973
  • 1
  • 15
  • 23