Blaszard
Blaszard

Reputation: 31975

How to save date type to an attribute of an entity in Core Data in Swift?

I want to set current date to my entity at the time when it is initialized by an user, so I tried to use NSDate and set its instance to the attribute in Swift, like:

task.date = NSDate() // task is an instance of Entity class

However, this code returns an error: NSDate is not a subtype of NSNumber. Actually this code worked in Objective-C, which is used in this post.

Note that I properly set the attribute's type to date in my xcdatamodeld file. Also, the other attribute (like title, which is just a string type) is successfully assigned the data to. So how can I use date to my Core Data object in Swift app?

Upvotes: 1

Views: 4217

Answers (1)

Mundi
Mundi

Reputation: 80273

You have to make sure that you have defined the NSManagedObject subclass correctly:

@objc(Task)
class Task: NSManagedObject {
    @NSManaged var date: NSDate
}

Tested. First line is optional for this scenario.

Upvotes: 1

Related Questions