开发者

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

开发者 https://www.devze.com 2023-02-02 08:57 出处:网络
I want to save & retrieve the timestamp of when the note was created in Core Data Please guide me on how I c开发者_运维知识库an do this.You can have your custom NSManagedObject subclass set an att

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

Please guide me on how I c开发者_运维知识库an do this.


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.


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

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

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消