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

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

问题描述

我有一个 NSArray 包含日期字符串 (即 NSString) 像这样:Thu, 21 May 09 19:10:09 -0700"

I have an NSArray that contains date strings (i.e. NSString) 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.

谢谢.

推荐答案

将日期作为 NSDate 对象存储在 NS(Mutable)Array 中,然后使用 -[NSArray sortedArrayUsingSelector:-[NSMutableArray sortUsingSelector:] 并通过 @selector(compare:) 作为参数.-[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天全站免登陆