NSArray的日期排序 [英] NSArray of Dates sort

查看:210
本文介绍了NSArray的日期排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个数组。它没有键,所以我不知道我可以使用NSSortDescriptor。

Consider this array. It has no keys, so I am not sure I can use NSSortDescriptor. What would be the best method to sort them?

(
    "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"
)


推荐答案

您可以使用 sortedArrayUsingFunction:

这里是一些示例代码。

Here's some example code.

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

有一个这些排序方法的数量< a> in NSArray。值得一看的是那些熟悉它们的人。

There are a number of these sorts of sort methods in NSArray. It's worth looking at those to familiarize yourself with them.

这篇关于NSArray的日期排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆