How to save the date and time when a Core Data object is created
You can have your custom NSManagedObject subclass set an attribute as soon as it's inserted in a context by overriding the -awakeFromInsert
method:
@interface Person : NSManagedObject
@property (nonatomic, copy) NSDate *creationDate; // modeled property
@end
@implementation Person
@dynamic creationDate; // modeled property
- (void)awakeFromInsert
{
[super awakeFromInsert];
self.creationDate = [NSDate date];
}
@end
Note that creationDate
above is a modeled property of Core Data attribute type "date", so its accessor methods are generated automatically. Be sure to set your entity's custom NSManagedObject class name appropriately as well.
You have a Note
entity with a created
attribute?
Set the default value to now()
Edit
Be away that setting now()
as the default means it will use the build time, not the current time. If you want to set it properly - you need to use an NSManagedObject subclass.
Make a Core Data entity called Note, give it an attribute called timeStamp Set it to type Date.
When creating a new Note assign it the current time:
[note setTimeStamp:[NSDate date]];
Persist the Note, that is it.
Just to keep this question up-to-date with Swift, in the xcdatamodelid
click the entity you wish to create a default date. Under the Data Model Inspector change Codegen from "Class Definition" to "Manual/None":
Then from the menu bar click Editor -> Create NSManagedObject Subclass...
and create the two Swift classes: Note+CoreDataClass.swift
and Note+CoreDataProperties.swift
Open the Note+CoreDataClass.swift
file and add the following code:
import Foundation
import CoreData
@objc(Note)
public class Note: NSManagedObject {
override public func awakeFromInsert() {
super.awakeFromInsert()
self.creationDate = Date() as NSDate
}
}
Now the creationalDate
will get a default date of the current date/time.