F.Chen F.Chen -4 years ago 41
iOS Question

How do sort a NSArray of weekdays?

I have an array of weekdays and the days can be at any positions of the array.

For example, my array could be Fri, Wed, Mon, Tue. So I want to sort it so it would be Mon, Tue, Wed, Fri.

How do I do that?

Answer Source

Start by mapping the day string to a numeric index:

NSArray *days = @[
  @"Mon",
  @"Tue",
  @"Wed",
  @"Thu",
  @"Fri",
  @"Sat",
  @"Sun"
];

NSUInteger dayIndex = [days indexOfObject:string];

Then you can simply sort the array using that, for example:

NSArray *sortedDays = [array sortedArrayUsingComparator:^NSComparisonResult(NSString *dayString1, NSString *dayString2) {
    NSUInteger dayIndex1 = [days indexOfObject:dayString1];        
    NSUInteger dayIndex2 = [days indexOfObject:dayString2]; 

    if (dayIndex1 < dayIndex2) {
        return NSOrderedAscending;
    }

    if (dayIndex1 > dayIndex2) {
        return NSOrderedDescending;
    }

    return NSOrderedSame;
}];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download