2

I am using Core Data and would like to run some custom code when setting a property.

@interface FTRecord : NSManagedObject

@property (nonatomic) NSTimeInterval timestamp;


@implementation FTRecord

@dynamic timestamp;

-(void)setTimestamp:(NSTimeInterval)newTimestamp
{
    //run custom code....

    //and now how to pass the value to the actual property?
    [self setTimestamp:newTimestamp];
}

In this case I have defined the setter body for the timestamp property. But how do I set the value of the property without running into a recursion loop?

Houman
  • 64,245
  • 87
  • 278
  • 460
  • @MartinR I don't think that's the same question -- the one you found is about dependent properties, not simply writing your own setter. – Jesse Rusak Oct 30 '13 at 20:04
  • @JesseRusak: You might be right, the questions are different, but the answers are the same (or at least very similar). – Martin R Oct 30 '13 at 20:10

1 Answers1

2

There's a magical accessor generated for each property, which in your case would be called setPrimitiveTimestamp: which you can use for this. Take a look at the docs for NSManagedObject's - (void)setPrimitiveValue:(id)value forKey:(NSString *)key.

So, you want:

-(void)setTimestamp:(NSTimeInterval)newTimestamp
{
    //run custom code....

    //and now how to pass the value to the actual property?
    [self willChangeValueForKey:@"timestamp"];
    [self setPrimitiveTimestamp:newTimestamp];
    [self didChangeValueForKey:@"timestamp"];
}
Jesse Rusak
  • 56,530
  • 12
  • 101
  • 102