0
votes

I have a simple NSArray which has some arrays as objects which has some dates and strings as objects:

  • NSArray (main array) ---------------> table view
    • NSArray (secondary array)---> table view cell
      • NSDate --------------------> table view cell text label
      • NSString -------------------> table view cell detail text label
      • etc.

I use the main array for my table view -> each cell got it's own 'secondary array'. Now I want to sort the main array by the NSDate object. It sounds very easy but I have found no solution on the web for it.

I thought about using NSSortDesriptors but those just sort the array by the objects in the main array and not in the secondary array.

Hopefully you can help me

EDIT: Would it fix the problem if I use a NSDictionary as the secondary array?

2

2 Answers

4
votes

You should be able to use NSArray sortedArrayUsingComparator if your app is targeted for iOS 4.0 or later:

NSArray *sortedArray = [mainArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
    return [[obj1 objectAtIndex:0] compare:[obj2 objectAtIndex:0]];
}];

This assumes that the date field is always in index 0 of the internal array. It would probably be a bit cleaner if you used a dictionary and keyed the date field by name, but if you are comfortable with the date field always remaining in index 0 then the above should work.

1
votes

Assuming I've understood your data structure correctly, this should be close:

NSArray *sortedArray = [mainArray sortedArrayUsingComparator:^(id ary1, id ary2) {
    NSArray *array1 = (NSArray *)ary1;
    NSArray *array2 = (NSArray *)ary2;
    NSDate *date1 = (NSDate *)[array1 objectAtIndex:0];
    NSDate *date2 = (NSDate *)[array2 objectAtIndex:0];
    return [date1 compare:date2];
}];