Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 按对象的NSDate属性对对象数组进行排序_Objective C_Nsmutablearray_Nsdate_Sorting - Fatal编程技术网

Objective c 按对象的NSDate属性对对象数组进行排序

Objective c 按对象的NSDate属性对对象数组进行排序,objective-c,nsmutablearray,nsdate,sorting,Objective C,Nsmutablearray,Nsdate,Sorting,可能重复: 如何通过访问对象的NSDate属性对对象数组进行排序 我知道可以使用[mutableArray sortUsingSelector:@selector(compare:)]在日期数组上,但如何通过访问数组中每个元素的NSDate属性来实现,按最早日期到最晚日期排序对象?您可以覆盖自定义类中的比较方法,以便它比较自定义类中的两个对象,并根据对象上的日期返回相应的NSComparisonResult 例如: -(NSComparisonResult)compare:(YourClass

可能重复:

如何通过访问对象的NSDate属性对对象数组进行排序


我知道可以使用
[mutableArray sortUsingSelector:@selector(compare:)]
在日期数组上,但如何通过访问数组中每个元素的NSDate属性来实现,按最早日期到最晚日期排序对象?

您可以覆盖自定义类中的比较方法,以便它比较自定义类中的两个对象,并根据对象上的日期返回相应的NSComparisonResult

例如:

-(NSComparisonResult)compare:(YourClass*)otherObject
{
   return [self.date compare:otherObject.date];
}
您可以使用:

   NSArray *sortedArray = [mutableArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        NSDate *first = [(Person*)a birthDate];
        NSDate *second = [(Person*)b birthDate];
        return [first compare:second];
    }];

或者看看这个

有一种方法叫做
-[NSArray sortedarrayingcomparator:
。这需要一个模块,在这个模块中,您可以实现您认为适合您的对象的任何比较。

感谢所有的答案,我找到了这个答案,解决了我的问题

以下是感谢用户的代码:NSGod:

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

为了使其更加简洁,您可以这样编写第二行:
[mutableArray sortusingsdescriptor:@[sortByDate]
要进一步澄清(如果需要),
排序描述符:
返回排序后的
NSArray
。您可能希望将其分配给另一个变量,并从中获取该变量。
NSSortDescriptor *dateDescriptor = [NSSortDescriptor
                                 sortDescriptorWithKey:@"startDateTime" 
                                             ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray *sortedEventArray = [nodeEventArray
     sortedArrayUsingDescriptors:sortDescriptors];