Search code examples
iosswiftrealm

How to store a time interval (hour:minute:second) in Realm swift


I'm currently creating a workout timer application. I want to store just the hour:minute:second of the created timer object.

I first created a Time object:

class Time: Object {
    @objc dynamic var hour: Int = 0
    @objc dynamic var minute: Int = 0
    @objc dynamic var second: Int = 0
}

And I was using this object to represent the time interval. What I don't like about this approach is I get a separate Time table with hour, minute and second columns.

I then wanted to see if I could store a tuple (Int, Int, Int) to represent my time interval. But I received a warning that the tuple type cannot be represented in object-c. I also figured Realm probably wouldn't know what to do with a tuple.

So my question is. Whats the best way to store a user selected hour, minute and second time interval without also having to store an entire date object with the useless date attached to it.

I, of course, also need the ability to read that time interval from the backing store so that I can apply it to a timer.

EDIT: I guess I could also just store it as a integer value of seconds and than parse that result in to hours, minutes, and seconds


Solution

  • Unless there are other prerequisites not described in the question, just use Swift's TimeInterval (typealias for Double, which is supported by Realm). I expect this is a property on some other modeled object (otherwise you're just storing arbitrary numbers) - let's say it's on a Workout object.

    class Workout: Object {
    
        @objc dynamic var interval: TimeInterval = 0
    
    }
    

    If you want to pull out the hour/minute/second of the time interval, the quick and dirty solution is to extension Double { } with utility functions like func inSeconds(). But the better solution is to use DateComponentsFormatter, which can take your TimeInterval as input and spit those things out while handling far more edge cases for you.