Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort NSArray using sortedArrayUsingFunction

Any good example of sorting a NSArray using sortedArrayUsingFunction ?

TY!

like image 738
Martha Avatar asked Feb 28 '11 20:02

Martha


2 Answers

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.

like image 72
hol Avatar answered Oct 03 '22 15:10

hol


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;
}
like image 44
Macmade Avatar answered Oct 03 '22 15:10

Macmade