Alex Rivera | Logout

adding non-persistent variables to nsmangedobject

Asked 2012-02-11T19:29:59.367
10

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.

  • should I just create ivars in my class, create the corresponding property and then synthesis them in the implementation?
  • should I not create ivars, and instead just declare the property and then @dynamic the property in the implmentation?
  • is there some other approach i should be taking?

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!

Edit
Report

2 Answers

10

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.

enter image description here

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
answered 2012-02-11T19:35:00.887
10

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.

answered 2012-02-13T09:41:28.810

Your Answer