I have difficulties with the following task: I have a NSMutableArray containing NSManagedObjects "OpeningHours" which I pull from core data.
NSMutableArray *openingHoursArray = [NSMutableArray arrayWithArray: [[museum valueForKey:@"openingHours"] allObjects]];
The array is unsorted, as getting the value for keys from my NSManagedObject "museum" returns a randomly organized set.
The NSManagedObjects "openingHours" in the array have values of type NSDate, accessible via the keys "start" and "end". Now, to display my Opening Hours in a way that makes sense, I access the weekday and time information of the respective dates, that works fine so far using this piece of code:
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:mainDelegate.localeCode];
NSDateFormatter *weekday = [[[NSDateFormatter alloc] init] autorelease];
[weekday setLocale:locale];
[weekday setDateFormat: @"EEEE"];
[NSDateFormatter *time = [[[NSDateFormatter alloc] init] autorelease];
[time setLocale:locale];
[time setTimeStyle:NSDateFormatterShortStyle];
for (NSManagedObject *openingHour in openingHoursArray) {
NSLog(@"%@", [openingHour valueForKey:@"start"]);
NSDate *startDate = [openingHour valueForKey:@"start"];
NSDate *endDate = [openingHour valueForKey:@"end"];
NSString *startDay = [weekday stringFromDate:startDate];
NSString *endDay = [weekday stringFromDate:endDate];
NSString *startTime = [time stringFromDate:startDate];
NSString *endTime = [time stringFromDate:endDate];
if (![startDay isEqualToString:endDay]) {
[openingHoursString appendFormat:@"%@ - %@:\t%@ - %@ \n", startDay, endDay, startTime, endTime];
}
else {
[openingHoursString appendFormat:@"%@:\t%@ - %@ \n", startDay, startTime, endTime];
}
}
This gives me the desired output:
Thursday: 10:00 AM - 9:00 PM
Friday - Sunday: 10:00 AM - 6:00 PM
Monday - Wednesday: 10:00 AM - 5:00 PM
Now the problem is: of course I want the Monday opening period to be displayed first. I need to sort my array by the weekday of the start date value. I tried sorting it using the following:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"start" ascending:TRUE];
[openingHoursArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
but obviously this doesn't work because it simply sorts by dates, and 1970-01-01 was unfortunately a thursday, therefore thursday will be the first item of my array sorted by above code.
Does anyone have a good idea on how to "sort this out"? :-) I'm completely stuck with this.. Thanks a lot!