Representing hourly ranges in Objective-C
I'm trying to create a class that represents hours of operation in an Obj-C program. I have been considering using NSDatesComponent
to do this, but I feel there should be an easier way. Does anyone have any tips as to how to do this?
In Core Data, I would have a shop
entity that would have an ivar that is an array. This array would have seven entries for each day of the week, and the value for each day would be an hoursOp
object that would represent a range of hours. 9-5, 10-6, etc. The issue is, I'm not sure how to create my hoursOp
class to represent a range of hours. I was thinking of using NSDateComponents
, but am unsure if I should bother. Currently, I think that an hoursOp
object should hold two variables: a starting time and an ending time.
Furthermore, this is complicated by the possible need for multiple hoursOp
objects in an array entry- what if a shop
has operating hours of 10-4, then 6-8? So instead of an 开发者_如何学编程array that holds hoursOp
object, it would be a two-dimensional array where each entry is an array of its own holding 1 or more hoursOp
objects. This is all a bit convoluted, but I believe I could get it to work, once I figure out how to represent the hours (or the ranges themselves, if anyone has a better suggestion).
It's hard to say the "best" way to implement this, because it depends on what you're doing with the data, but if you stored the day of the week, opening time and closing time inside your hoursOp
object, you could have a one-dimensional array of hoursOp
objects that represented time intervals when the store was open.
You'd lose the one-to-one relationship between your array index and the day of the week, which might make some tasks harder (if you're constantly querying this object for its Saturday store hours, for instance, you'll be scanning the entire array a lot), but otherwise you're going down the path of having an array of arrays.
This is what I ended up doing, using NSDate
and NSDateFormatter
only, where open is an NSString
formatted in military time.
-(void) setOpeningTimeWithString: (NSString *)open
{
NSDateFormatter * formatFromInput = [[NSDateFormatter alloc] init];
[formatFromInput setDateFormat:@"HH:mm"];
self.openingTime = [formatFromInput dateFromString:open];
[formatFromInput release];
}
The takeaway lesson is that it's perfectly okay to have NSDate
objects where you only set the hourly components- everything else is only set to January 1, 1970, and it doesn't cause any issues.
精彩评论