NSManagedObject Property Timestamp Authentication

I have an NSManagedObject with two properties:

 NSNumber *score; NSDate *score_timestamp; 

I need to update the score_timestamp field every time I update the score .

I obviously cannot use the -willSave method, since my context is sometimes saved and score_timestamp will not be updated. Therefore, I must either override -setScore: or configure my managed entity as an observer with a key for my own score field.

-setScore: solution -setScore: seems simple:

 - (void) setScore:(NSNumber *)score { [self willChangeValueForKey:@"score"]; [self setPrimitiveScore:score]; [self didChangeValueForKey:@"score"]; self.score_timestamp = [NSDate date]; } 

Are there any warnings on this? Or should I use a KVO solution?

Update

So far I have received two answers that my code will not work through setValue: forKey: and I'm still waiting, for example. A naive call to [(NSManagedObject *)myObject setValue:value forKey:@"score"] still calls my setter.

So, if I switch to the KVO solution, should I addObserver: in all awake methods and delete it in willTurnIntoFault ? Or is it not that simple?

+7
source share
3 answers

The implementation in your question is fine. Any KVC attempt to update your value will also go through the setter method ( setValue: forKey: just looking for the access method matching setKey , see here for details).

+4
source

You are looking for Key Values โ€‹โ€‹Monitoring

 [objectWithArray addObserver:self forKeyPath:@"score" options:NSKeyValueObservingOptionNew context:nil]; 

Then, to watch this:

 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { //Check if [change objectForKey:NSKeyValueChangeNewKey] is equal to "score" //and update the score_timestamp appropriately } 

You must register to be notified when you wake up when checking out and unregistering when I am wrong.

+1
source

In this method, if for any reason you change the object not as your own subclass, but as NSManagedObject using setValue: forKey: date will not be updated.

0
source

All Articles