3

この配列を検討してください。キーがないため、NSSortDescriptor を使用できるかどうかわかりません。それらをソートする最良の方法は何ですか?

(
    "Thursday, July 30, 2009",
    "Monday, September 07, 2009",
    "Wednesday, September 09, 2009",
    "Friday, August 14, 2009",
    "Saturday, September 05, 2009",
    "Monday, August 10, 2009",
    "Thursday, July 23, 2009",
    "Monday, October 12, 2009",
    "Friday, October 16, 2009",
    "Monday, August 17, 2009",
    "Tuesday, October 13, 2009",
    "Wednesday, September 30, 2009",
    "Sunday, August 16, 2009",
    "Thursday, August 27, 2009",
    "Monday, August 31, 2009",
    "Saturday, August 15, 2009",
    "Thursday, August 06, 2009",
    "Saturday, September 26, 2009",
    "Tuesday, September 29, 2009",
    "Tuesday, September 15, 2009",
    "Tuesday, September 01, 2009"
)
4

2 に答える 2

12

使用できますsortedArrayUsingFunction:

コード例を次に示します。

NSInteger dateSort(id s1, id s2, void *context)
{
    NSDateFormatter* format = (NSDateFormatter*)context;
    NSDate* d1 = [format dateFromString:s1];
    NSDate* d2 = [format dateFromString:s2];

    return [d1 compare:d2];
}

...

-(void)someObjectiveCMethod
{
    NSDateFormatter* format = [[[NSDateFormatter alloc] init] autorelease];

    // Find theses format codes here:
    // http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
    //
    [format setDateFormat:@"EEEE, MMMM dd, yyyy"];

    NSArray* myArray = getMyArray();
    NSArray* sortedArray = [myArray sortedArrayUsingFunction:dateSort context:format];
}

NSArrayには、これらの種類の並べ替えメソッドが多数あります。それらに慣れるためにそれらを見る価値があります。

于 2009-10-23T14:39:44.180 に答える
3
NSArray * unsortedDates = ...;
NSArray * sortedDates = [unsortedDates sortedArrayUsingSelector:@selector(compare:)];
于 2009-10-23T14:43:40.010 に答える