user440485
user440485

Reputation: 797

How to save the date and time when a Core Data object is created

I want to save & retrieve the timestamp of when the note was created in Core Data

Please guide me on how I can do this.

Upvotes: 18

Views: 17289

Answers (4)

Abizern
Abizern

Reputation: 150615

You have a Note entity with a created attribute?

Set the default value to now()

Edit

Be aware 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.

Upvotes: 2

Rafael
Rafael

Reputation: 7242

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":

enter image description here

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 creationDate will get a default date of the current date/time.

Upvotes: 4

Chris Hanson
Chris Hanson

Reputation: 55116

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.

Upvotes: 51

RickiG
RickiG

Reputation: 11390

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.

Upvotes: 11

Related Questions