Sort NSArray using sortedArrayUsingFunction

蓝咒 提交于 2019-11-29 14:22:35
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.

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

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!