排序NSArray日期字符串或对象 [英] Sort NSArray of date strings or objects

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

问题描述

我有一个 NSArray ,包含如下的日期字符串:Thu,21 May 09 19:10:09 -0700

I have an NSArray that contains date strings like this: "Thu, 21 May 09 19:10:09 -0700"

我需要按日期对 NSArray 进行排序。我想先将日期字符串转换为 NSDate 对象,但是卡在那里,如何通过 NSDate 对象。

I need to sort the NSArray by date. I thought about converting the date string to an NSDate object first, but got stuck there on how to sort by the NSDate object.

感谢。

推荐答案

在NS(Mutable)数组中的c $ c> NSDate 对象,然后使用 - [NSArray sortedArrayUsingSelector: or < a href =http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/sortUsingSelector: =nofollow noreferrer > - [NSMutableArray sortUsingSelector:] 并传递 @selector(compare:) / strong>作为参数。 - [NSDate compare:] 方法将按升序对日期进行排序。这比创建一个 NSSortDescriptor 更简单,比写自己的比较函数简单得多。 ( NSDate 对象知道如何至少与我们希望使用自定义代码完成一样有效)。

Store the dates as NSDate objects in an NS(Mutable)Array, then use -[NSArray sortedArrayUsingSelector: or -[NSMutableArray sortUsingSelector:] and pass @selector(compare:) as the parameter. The -[NSDate compare:] method will order dates in ascending order for you. This is simpler than creating an NSSortDescriptor, and much simpler than writing your own comparison function. (NSDate objects know how to compare themselves to each other at least as efficiently as we could hope to accomplish with custom code.)

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

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