To avoid the infinite loop, you could set the last modification date using the primitive accessor:
[object setPrimitiveValue:dateOfTheLastModification forKey:@"lastModifiedDate"];
because that does not fire another "change" notification. But that also implies that no observers will see the change.
Overriding willSave
in the managed object subclass would suffer from the same problem.
The Apple documentation for willSave
states:
For example, if you set a last-modified timestamp, you should check whether either you previously set it in the same save operation, or that the existing timestamp is not less than a small delta from the current time. Typically it’s better to calculate the timestamp once for all the objects being saved (for example, in response to an
NSManagedObjectContextWillSaveNotification
).
So you should register for NSManagedObjectContextWillSaveNotification
instead,
and set the timestamp on all updated and inserted objects in the managed object
context. The registered method could look like this:
-(void)contextWillSave:(NSNotification *)notify
{
NSManagedObjectContext *context = [notify object];
NSDate *dateOfTheLastModification = [NSDate date];
for (NSManagedObject *obj in [context insertedObjects]) {
[obj setValue:dateOfTheLastModification forKey:@"lastModifiedDate"];
}
for (NSManagedObject *obj in [context updatedObjects]) {
[obj setValue:dateOfTheLastModification forKey:@"lastModifiedDate"];
}
}
This assumes that all your entities have a lastModifiedDate
attribute, otherwise
you have to check the class of the objects.