I have a subclass of an NSManagedObject, and I'd like to add a couple ivars to keep track of some book-keeping. I don't want these vars to persist, and so that is why I don't include them as part of the data model.
I'm having trouble finding the proper way of doing this.
And should I be doing all the customization in the my NSManagedObject subclass, or should I be creating a subclass of my subclass, so that if I change my data model I won't lose all my customizations when I get xcode to generate my NSManagedObject subclass automatically?
Thanks!
The documentation for NSManagedObject
has a section called Custom Instance Variables. It discusses both approaches.
Both transient, modeled attributes and ivars are good solutions. It depends on taste and style.
One very important point to remember if you use ivars: You need to clear out ivars in - (void)didTurnIntoFault
and set any initial values in - (void)awakeFromFetch
and - (void)awakeFromInsert
. You need to not touch any modeled attributes or relationships inside -didTurnIntoFault
or else you'll get in trouble.
Each attribute for NSManagedObject
has a checkbox named transient. This way you'll have dynamic accessors for the object without actually persisting the property value itself. Look for checkbox right under the text field for attribute name entry.
UPDATE If you don't want to create a migration because of new attributes, make standard ivars
@interface MyMO : NSManagedObject {
NSString *_nonPersistentAttribute;
}
@property (nonatomic, retain) NSString *nonPersistentAttribute;
@end
@implementation MyMO
@synthesize nonPersistentAttribute=_nonPersistentAttribute;
@end
Wise,
To your first question re: ivars, you have two choices standard ivars or transient attributes on your entity. The big difference between the two is that the transient attributes participate in the change/dirty/undo aspects of Core Data. If your ivars don't need that, then don't use the transient attributes. (Yes, use @property
and @synthesize
for your ivars.)
To your second question re: where to make the changes? I am somewhat of a luddite. The header patterns automatically generated by Xcode are pretty simple. Hence, I use the auto generated files for the first time I create an entity and edit in my changes thereafter. Frankly, you don't change your model data structures very often. Hence, adding a few lines here and there to both .h&.m files isn't a big cost. There are other mechanisms. Wolf Rentzch's mogenerator system is well respected and useful. That said, I'm not convinced that mogenerator solves a problem faced by modern Objective-C v2 Core Data programmers. (Obj-C v2 has made many things easier for Core Data programmers.)
Andrew
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With