TAGS :Viewed: 9 - Published at: a few seconds ago

[ How to sort NSMutableArray of NSMutableDictionary? ]

I have NSMutableArray of NSMutableDictionary(NSString objects). One of NSString object is actually a date, and i need to sort NSMutableArray based on that date and I don't want it to sort dates as strings. How can i make it?

Answer 1


If I understand correctly, your array contains dictionaries that contain strings and you want to sort on those strings... as dates. Something like this perhaps:

[someArray sortWithOptions: 0 usingComparator: ^(id inObj1, id inObj2) {
    NSDate      *date1 = [NSDate dateWithString: [inObj1 objectForKey: @"dateString"]];
    NSDate      *date2 = [NSDate dateWithString: [inObj2 objectForKey: @"dateString"]];

    return [date1 compare: date2];
}];

Answer 2


You will need to use the sortedArrayUsingFunction:context: method. For example:

NSInteger comparator( NSDictionary *d1, NSDictionary *d2, void *context )
{
  return [[d1 objectForKey:@"date"] compare:[d2 objectForKey:@"date"]];
}

// In some method:
NSArray *sortedArray = [array sortedArrayUsingFunction:comparator context:nil];

Note: This is not tested.