iphone – Objective-C:按工作日排序NSDates的NSMutableArray

我遇到以下任务有困难:我有一个NSMutableArray包含NSManagedObjects“OpeningHours”,我从核心数据中提取.

NSMutableArray *openingHoursArray = [NSMutableArray arrayWithArray: [[museum valueForKey:@"openingHours"] allObjects]];

数组未排序,因为从我的NSManagedObject“博物馆”获取键的值会返回一个随机组织的集合.

数组中的NSManagedObjects“openingHours”具有NSDate类型的值,可通过键“start”和“end”访问.现在,以一种有意义的方式显示我的营业时间,我访问相应日期的工作日和时间信息,到目前为止使用这段代码工作正常:

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];             
        }

    }

这给了我想要的输出:

周四:上午10:00 – 晚上9:00

周五 – 周日:上午10:00 – 下午6:00

周一至周三:上午10:00至下午5:00

现在的问题是:我当然希望首先显示星期一的开放时间.我需要按开始日期值的工作日对数组进行排序.我尝试使用以下方法对其进行排序:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"start" ascending:TRUE];
[openingHoursArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

但显然这不起作用,因为它只按日期排序,并且不幸的是1970-01-01星期四,因此星期四将是我的数组的第一项按上面的代码排序.

有没有人对如何“解决这个问题”有一个好主意? :-)我完全坚持这个..
非常感谢!

最佳答案 这样的事情应该有效:

NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSArray *sortedArray = [openingHoursArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
    NSDate *startDate1 = [obj1 valueForKey:@"start"];
    NSDate *startDate2 = [obj2 valueForKey:@"start"];
    NSDateComponents *components1 = [calendar components:NSWeekdayCalendarUnit fromDate:startDate1];
    NSDateComponents *components2 = [calendar components:NSWeekdayCalendarUnit fromDate:startDate2];
    NSInteger weekday1 = [components1 weekday];
    if (weekday1 == 1) weekday1 = 8; //Order sundays last
    NSInteger weekday2 = [components2 weekday];
    if (weekday2 == 1) weekday2 = 8;
    return [[NSNumber numberWithInteger:weekday1] compare:[NSNumber numberWithInteger:weekday2]];
}];
点赞