I ended up finding similar questions/answers on StackOverflow (https://stackoverflow.com/a/10723861/123016 and https://stackoverflow.com/a/4590190/123016). I adapted the suggested solutions to suit my needs.
What I first did, is create an abstract entity which I used as the parent class of all other entities. This abstract class has two properties: createdAt
and updatedAt
.
I then added the following code to the implementation of the abstract class:
- (void)awakeFromInsert
{
[super awakeFromInsert];
self.createdAt = [NSDate date];
}
+ (void)load
{
@autoreleasepool {
[[NSNotificationCenter defaultCenter] addObserver:(id)self.class
selector:@selector(objectContextWillSave:)
name:NSManagedObjectContextWillSaveNotification
object:nil];
}
}
+ (void)objectContextWillSave:(NSNotification *)notification
{
NSManagedObjectContext *context = [notification object];
NSSet *allObjects = [context.insertedObjects setByAddingObjectsFromSet:context.updatedObjects];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self isKindOfClass: %@", [self class]];
NSSet *allModifiableObjects = [allObjects filteredSetUsingPredicate:predicate];
[allModifiableObjects makeObjectsPerformSelector:@selector(setUpdatedAt:) withObject:[NSDate date]];
}
Apart from the fact that I made the parent class abstract, this is exactly the same code as both answers combined.