使用sortedArrayUsingFunction对NSArray进行排序

时间:2011-02-28 20:29:57

标签: iphone cocoa-touch ios cocoa nsarray

使用sortedArrayUsingFunction排序NSArray的任何好例子?

TY!

3 个答案:

答案 0 :(得分: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]); 
}

这个我习惯按预订排序。 Booking是一个带有合成实例变量的类,名为BOOKING_DATE。

答案 1 :(得分:1)

如文件中所述: 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;
}

答案 2 :(得分:1)

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