简体   繁体   English

按对象方法的结果对NSArray进行排序

[英]Sort NSArray by the results of the object's method

So I have an NSArray with custom objects called Church. 所以我有一个名为Church的自定义对象的NSArray。 And in each church there is an array of mass times. 每个教堂都有一系列的群众时光。 So there is a method in church which calculates the closest mass to the user's current time. 因此教会中有一种方法可以计算出与用户当前时间最接近的质量。

-(NSDate *)closestTimeTo:(NSDate *)currentTime

I want to be able to sort the NSArray of Church by the results (which are NSDate) returned by that method for each object. 我希望能够通过该方法为每个对象返回的结果(NSDate)对教会的NSArray进行排序。 Basically to get a sorted list of masses sorted by the closest time and also location. 基本上是获得按最近时间和位置排序的按质量排序列表。

I'm using categories and can't store the closest times as properties since its a core data object. 我正在使用类别,因为它是核心数据对象,所以无法将最接近的时间存储为属性。 I also don't think its a good idea to save those values to core data as these methods will be called constantly due to location services. 我也不认为将这些值保存到核心数据是一个好主意,因为这些方法将由于位置服务而不断调用。

Any ideas on how I can sort such array using the result of its objects' method? 关于如何使用对象方法的结果对这样的数组进行排序的任何想法?

Try the following block. 尝试以下块。 It would help directly(or at least with minor modifications). 这将有助于直接(或至少进行微小修改)。

NSArray *sortedArray;
sortedArray = [yourArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSDate *first = [(Church*)a closestTimeTo:currentTime];
    NSDate *second = [(Church*)b closestTimeTo:currentTime];
    return [first compare:second];
}];

Make a new method in your class that takes another Church class and returns NSOrderedSame , NSOrderedAscending or NSOrderedDescending , depending on whether you want that object to be first or last. 在类中创建一个新方法,该方法接受另一个Church类并返回NSOrderedSameNSOrderedAscendingNSOrderedDescending ,具体取决于您是希望该对象是第一个还是最后一个。 Use your closestTimeTo method to find that out. 使用您的closestTimeTo方法找出它。 Then use NSArray 's sortedArrayUsingSelector call with your method. 然后使用NSArraysortedArrayUsingSelector调用您的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM