按 NSDate 属性对自定义对象的 NSArray 进行排序 [英] Sort NSArray of custom objects by their NSDate properties

查看:36
本文介绍了按 NSDate 属性对自定义对象的 NSArray 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对填充了自定义对象的 NSArray 进行排序.每个对象都有一个 NSDate 类型的属性 startDateTime.

I am attempting to sort an NSArray that is populated with custom objects. Each object has a property startDateTime that is of type NSDate.

以下代码生成一个数组,sortedEventArray,已填充但未排序.我是完全错误的方法还是我只是遗漏了一些小东西?

The following code results in an array, sortedEventArray, populated but not sorted. Am I going about this the completely wrong way or am I just missing something small?

NSSortDescriptor *dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"startDateTime" 
                                                                 ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray *sortedEventArray = [nodeEventArray sortedArrayUsingDescriptors:sortDescriptors];

推荐答案

您确定节点事件的 startDateTime 实例变量非 nil 吗?

Are you sure that the startDateTime instance variables of the node events are non-nil?

如果您还没有,您可以向节点事件对象添加一个(自定义)-description 方法,该方法执行如下操作:

If you don't have one already, you might add a (custom) -description method to your node event objects that does something like this:

- (NSString *)description {
   return [NSString stringWithFormat:@"%@ - %@",
                   [super description], startDateTime]];
}

然后在您的排序代码中记录之前和之后的数组:

Then in your sorting code log the array before and after:

NSLog(@"nodeEventArray == %@", nodeEventArray);
NSSortDescriptor *dateDescriptor = [NSSortDescriptor
                                     sortDescriptorWithKey:@"startDateTime" 
                                                 ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray *sortedEventArray = [nodeEventArray
         sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"sortedEventArray == %@", sortedEventArray);

如果 startDateTime 都是 nil,那么 before 和 after 数组将具有相同的顺序(因为排序操作将等同于发送所有 nil>-compare: 消息到 nil,基本上什么都不做.

If the startDateTime's are all nil, then the before and after arrays will have the same order (since the sorting operation will equate to sending all the -compare: messages to nil, which basically does nothing).

这篇关于按 NSDate 属性对自定义对象的 NSArray 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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