如何通过 NSDates 和 NSStrings 对数组重新排序
我有一个数组,其中包含我的一个名为“游戏”的自定义类。每个“游戏”都包含一个 NSDate。我想根据日期重新排序我的数组,以便它们按从最新到最旧的顺序排列。我怎么能这么做呢?另外,我的“游戏”类包含一个 NSString。我如何重新排序我的数组以便游戏按字母顺序排列?
I have an array that contains a custom class of mine called 'Game'. Each 'Game' contains an NSDate. I would like to reorder my Array based on the dates so that they are in order from newest to oldest. How could I do that? Also, my class 'Game' contains an NSString. How could I reorder my Array so that the games are alphabetized?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一种非常简单的方法可以做到这一点,那就是使用
NSSortDescriptor
:Apple 已经编写了排序代码。它只需要知道按哪些属性进行排序。这就是
NSSortDescriptor
所封装的内容。一旦你得到了一个,只需将它交给数组,数组就会返回一个排序版本。 (或者,如果您有NSMutableArray
,则可以使用-sortUsingDescriptors:
对它进行就地排序)There's a REALLY simple way to do this, and that's with an
NSSortDescriptor
:Apple's already written the sorting code. It just needs to know what properties to sort by. That's what an
NSSortDescriptor
encapsulates. Once you've got one, simply give it to the array, and the array give you back a sorted version. (Alternatively, if you have anNSMutableArray
, you can sort it in-place using-sortUsingDescriptors:
)该数组必须是 NSMutableArray 对象,然后才能重新排序,如果我错了,请纠正我。
为了对数组进行排序,您需要在 Game 类中编写自定义排序方法。例如:
然后:
比较日期:
另请注意,如果您的数组包含不响应这些选择器的对象,因此该对象不是 Game 对象,您将收到异常,并且您的应用程序可能会崩溃
The array must be an NSMutableArray object before you can re-order it, correct me if I am wrong.
In order to sort the array you need to write a custom sort method in the Game class. Something like:
Then:
Comparing dates:
Also note that in the event of your array containing an object that does not respond to these selectors, thus an object that is not a Game object that you will get an exception, and that your app might break