Raja Rupinder Singh
Raja Rupinder Singh

Reputation: 59

How to store only time in CoreData without date component using UIDatePicker in Swift?

I am using UIDatePicker in my app to select time without date and storing its value in CoreData. But date value also gets stored if I use datePicked.date (datePicked is UIDatePicker) in my code. I know I can use NSDateFormatter to store HH:mm a format but I don't want to store string in my data model. Even if I store dateFromString function to store time in required format the default date is added along with time. Please tell me how can I store only time without date. Any help will be appreciated.

Upvotes: 3

Views: 1991

Answers (1)

Lumialxk
Lumialxk

Reputation: 6369

Updated
You can save transformable values in Core Data. Like this class:

class Time: NSValueTransformer {
let hour: Int
let minute: Int
let second: Int

override init() { // only sample code
    hour = 0
    minute = 0
    second = 0
}

override class func transformedValueClass() -> AnyClass {
    return NSNumber.self
}

override func reverseTransformedValue(value: AnyObject?) -> AnyObject? {
    guard let number = value as? NSNumber else {
        return nil
    }
    return Time() // you should init Time from the number
}

override func transformedValue(value: AnyObject?) -> AnyObject? {
    let number = hour * 60 * 60 + minute * 60 + second
    return number
}

override class func allowsReverseTransformation() -> Bool {
    return true
}
}

You should add transformable attribute like this: enter image description here And you will get this in model file:

extension Entity {

    @NSManaged var time: Time? // modify it to Time manually

}

And now, you can save Time to managed object.

Upvotes: 2

Related Questions