5

Any good example of sorting a NSArray using sortedArrayUsingFunction ?

TY!

3 Answers 3

7
NSArray *sorted_bookings = [myUnsortedArray sortedArrayUsingFunction:Sort_Bookingdate_Comparer context:self];   

NSInteger Sort_Bookingdate_Comparer(id id1, id id2, void *context)
{
    // Sort Function
    Booking* booking1 = (Booking*)id1;  
    Booking* booking2 = (Booking*)id2;  


    return ([booking1.BOOKING_DATE compare:booking2.BOOKING_DATE]); 
}

This I used to sort bookings by bookingdate. Booking is a class with a synthesized instance variable called BOOKING_DATE.

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

2 Comments

I was wondering if it returned a sorted array or if it sorts the array (myUnsortedArray) itself. Iguess ur example answers that. TY!
In my case I wanted a new array. But if your array is a NSMutableArray there is an instance method that just sorts the array. Just as in the example of Bogatyr
1

As stated in the documentation: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html

NSInteger intSort(id num1, id num2, void *context)
{
    int v1 = [num1 intValue];
    int v2 = [num2 intValue];
    if (v1 < v2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}

Comments

1

Close analogue using NSMutableArray:

[opponentMatchDicts sortUsingFunction:compareMatchByDate context:nil];
...


static int compareMatchByDate( id m1, id m2, void *context)
{
    NSDictionary *mDict1 = (NSDictionary *) m1;
    NSDictionary *mDict2 = (NSDictionary *) m2;
    NSDate *date1 = [mDict1 objectForKey:kMatchNSDate];
    NSDate *date2 = [mDict2 objectForKey:kMatchNSDate];

    int rv = [date1 compare:date2];
    return rv;
}

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.