通过NSDate属性对自定义对象的NSArray进行排序 [英] Sort NSArray of custom objects by their NSDate properties
问题描述
我试图对用自定义对象填充的NSArray进行排序。每个对象都有属性 startDateTime
,类型为NSDate。
以下代码产生一个数组, sortedEventArray
,填充但未排序。
NSSortDescriptor * dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:@ startDateTime
ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray * sortedEventArray = [nodeEventArray sortedArrayUsingDescriptors:sortDescriptors];
您确定 startDateTime
节点事件的实例变量是否为nil?
如果您还没有,您可以为您的节点添加(自定义) -description
事件对象,它执行这样的事情:
- (NSString *)description {
,则前后数组将具有相同的顺序(因为排序操作等于发送所有
return [NSString stringWithFormat:@ %@ - %@,
[super description],startDateTime]];然后在你的排序代码中记录数组之前和之后:NSLog(@nodeEventArray ==%@,nodeEventArray);
NSSortDescriptor * dateDescriptor = [NSSortDescriptor
sortDescriptorWithKey:@startDateTime
Descending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray * sortedEventArray = [nodeEventArray
sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@sortedEventArray ==%@,sortedEventArray);
如果
startDateTime
code> nil-compare:
消息到nil
,基本上什么也不做)。I am attempting to sort an NSArray that is populated with custom objects. Each object has a property
startDateTime
that is of type NSDate.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];
解决方案Are you sure that the
startDateTime
instance variables of the node events are non-nil?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);
If the
startDateTime
's are allnil
, then the before and after arrays will have the same order (since the sorting operation will equate to sending all the-compare:
messages tonil
, which basically does nothing).这篇关于通过NSDate属性对自定义对象的NSArray进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!