How do I sort NSMutableArray from NSMutableDictionary?

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

+2


a source to share


2 answers


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



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

      

+6


a source


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

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 has not been verified.

+1


a source







All Articles