Question

I have an entity with an attribute time, which is of type Date. I only care about the time component of it. When generating the class files, I chose to use scalar properties for primitive data types. So, NSTimeInterval is used instead of NSDate.

To store the time attribute , I has to parse strings with NSDateFormatter before assigning it to the entity:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"H:mm"];

NSTimeInterval time = [[dateFormatter dateFromString:@"19:20"] timeIntervalSince1970];
entity.time = time;

When using a predicate to fetch the records, I again used NSDateFormatter to "truncate" the date component:

NSDate *timeNow = [self.defaultDateFormatter dateFromString:
    [self.defaultDateFormatter stringFromDate:[NSDate date]]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"time >= %@", timeNow];
// build the rest of the NSFetchRequest...

The problem is, all records came back: some records had time attributes before timeNow and some were after. Bue when I compared timeNow with the time attributes of the returned records using [NSDate compare:], it actually returned the right outcomes!

Where went wrong?

Was it helpful?

Solution

If I understand well, you need to keep track of the time H:mm. The day, month and year is of no interest. Right?

Why not using an int16_t if you need minute resolution (max 1440) or an int32_t if you need second resolution (max 86400), and some very basic methods to convert from the base unit to something that suits your needs best like NSDateComponents for NSCalendar calculations? NSDate and NSTimeInterval aren't well suited to the task, are they?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top