0

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 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I tried your code in SDK 4.3 but I have get the following error: "[__NSCFArray compare:]: unrecognized selector sent to instance"
I made an update to the code sample right after I posted initially: Any chance you grabbed the previous version instead of the updated one?
yes only the previous version of your code resulted in the error code.
but it won't work for me ... I think I will change the secondary array into a dictionary that might be easier for me
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.