Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to save & retrive current time (if today) or date of the note created in Core Data

Please guide me on how I can do this.

like image 553
user440485 Avatar asked Jan 03 '11 11:01

user440485


People also ask

How is date stored in Core Data?

In a Core Data store, a Date attribute is a double value that represents a number of seconds since 1970. Using a variety of calendars, time zones, and locales, an app can convert a Date value to different date strings, or convert a date string to different Date values.

How do I save an object in Core Data?

To save an object with Core Data, you can simply create a new instance of the NSManagedObject subclass and save the managed context. In the code above, we've created a new Person instance and saved it locally using Core Data.

Can you store an array in Core Data?

There are two steps to storing an array of a custom struct or class in Core Data. The first step is to create a Core Data entity for your custom struct or class. The second step is to add a to-many relationship in the Core Data entity where you want to store the array.


1 Answers

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.

like image 92
Chris Hanson Avatar answered Oct 09 '22 05:10

Chris Hanson