1

I have an entity with several properties, one of them called lastModificationDate. Whenever any of the object's properties is set, I'd like to update the lastModificationDate.

If I were not using Core Data, I would just provide my own setter for the properties and update lastModificationDate. However, I'm not sure if I should mess around with CoreData's properties.

What's the best way to do this?

cfischer
  • 24,452
  • 37
  • 131
  • 214
  • Possible duplicate of [Custom setter methods in Core-Data](https://stackoverflow.com/questions/2971806/custom-setter-methods-in-core-data) – malhal Mar 16 '18 at 23:36

2 Answers2

1

Overriding the setters can easily be done, you have to make sure you fire the right notifications for everything else to work (including KVO).

- (void) setThing:(NSObject *)myThing {
  self.lastUpdateDate = [NSDate date];
  [self willChangeValueForKey:@"thing"];
  [self setPrimitiveThing:myThing];
  [self didChangeValueForKey:@"thing"];
}

This being said, if all you need to do is the code I showed (essentially setting the value and updating the last update date), you are much better off using Key-Value Observing and reacting to the notifications. It's easier and cleaner.

mprivat
  • 21,582
  • 4
  • 54
  • 64
  • If the core data framework changes behind the scenes, that could break catastrophically. But yes, that would work for now. – Jack Lawrence May 25 '12 at 12:19
  • Actually while it's recommended (for other reasons than the one you mention) to not implement custom accessors, this technique is amply documented in [Apple's documentation](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdAccessorMethods.html#//apple_ref/doc/uid/TP40002154-SW14) – mprivat May 25 '12 at 13:00
0

You shouldn't override property mutators (setters) if you're working with an NSManagedObject subclass because those implementations are provided at runtime (hence @dynamic instead of @synthesize). You could if you really wanted to, but it's messier and there's no reason to. Use Key Value Observing (KVO) instead. It'll let you know when a value is changed.

Apple's KVO documentation is great: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html#//apple_ref/doc/uid/10000177i

Jack Lawrence
  • 10,664
  • 1
  • 47
  • 61
  • 2
    Yes KVO is most likely the right solution but the rest of your answer is wrong. Check the Core Data Programming Guide [Managed Object Accessor Methods](http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/coredata/Articles/cdAccessorMethods.html#//apple_ref/doc/uid/TP40002154-SW5). There is also actually a code snippet in Xcode's snippet library called `Core Data property Accessors` that gives your the basic outline of how to override these methods. – Paul.s May 25 '12 at 12:09
  • There may well be no point but your answer stated that you couldn't do it, hence my comment. – Paul.s May 25 '12 at 12:24