为对象double属性排序数组

时间:2013-11-22 02:56:08

标签: ios objective-c arrays sorting

我需要使用其中对象的属性重新排序NSMutableArray。

我为之前项目中的日期做了这个日期,但这个方法不接受双打:

NSUInteger rowIndex = [self.alist indexOfObject:assignment inSortedRange:NSMakeRange(0, self.alist.count) options:NSBinarySearchingInsertionIndex usingComparator:^(AssignmentInfo *obj1, AssignmentInfo *obj2) {

    NSDate *date1 = obj1.dateTime;
    NSDate *date2 = obj2.dateTime;

    if ([date1 compare:date2] == NSOrderedAscending) {
        return NSOrderedAscending;
    }
    if ([date1 compare:date2] == NSOrderedDescending) {
        return NSOrderedDescending;
    }
    return NSOrderedSame;

}];

所以我不需要为数组中的社区对象的double值重新排序数组self.communitiesArrayself.community.distanceFromUser这是双倍的。

使用下面的一些答案我收到了错误:

NSUInteger rowIndex = [self.communitiesArray indexOfObject:community inSortedRange:NSMakeRange(0, self.communitiesArray.count) options:NSBinarySearchingInsertionIndex usingComparator:^(Community *obj1, Community *obj2) {

错误说:不兼容的块指针类型将'void(^)(Community * _ strong,Community * _strong)'发送到'NSComparator'类型的参数(又名'NSComparisonResult(^)(__ strong) id,__strong id)')

4 个答案:

答案 0 :(得分:3)

由于double是原语,因此您不需要对它们使用compare:方法:将它们与常规运算符进行比较就足够了。您的比较器块看起来如下:

double d1 = obj1.doubleValue;
double d2 = obj2.doubleValue;
if (d1 < d2) {
    return NSOrderedAscending;
}
if (d1 > d2) {
    return NSOrderedDescending;
}
return NSOrderedSame;

更好的方法是使用NSSortdescriptor:它们允许您根据公开的属性对对象进行排序,而无需编写任何其他代码:

NSSortDescriptor *dblDescr= [[NSSortDescriptor alloc] initWithKey:@"doubleValue" ascending:YES];
NSArray *sortedArray = [myData sortedArrayUsingDescriptors:@[dblDescr]];

答案 1 :(得分:3)

您可以使用NSSortDescriptor对数组进行排序。

[array sortUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey:@"community.distanceFromUser" ascending:YES]]];

答案 2 :(得分:0)

直接比较double s,即比较器:

double a = obj1.distanceFromUser;
double b = obj2.distanceFromUser;
if (a < b) {
    return NSOrderedAscending;
} else if (a > b) {
    return NSOrderedDescending;
} else {
    return NSOrderedSame;
}

答案 3 :(得分:0)

正如其他人所说,double是原始类型,因此您可以使用比较运算符来比较它们

NSUInteger rowIndex =
     [self.communitiesArray indexOfObject:community
                            inSortedRange:NSMakeRange(0, self.communitiesArray.count)
                                  options:NSBinarySearchingInsertionIndex
                          usingComparator:^NSComparisonResult (Community *obj1, Community *obj2) {
       double distance1 = obj1.distanceFromUser;
       double distance2 = obj2.distanceFromUser;
       if (distance1 < distance2)
           return NSOrderedAscending;
       if (distance1 < distance2)
           return NSOrderedDescending;
       return NSOrderedSame;
}

注意块签名:您传递的^(Community *obj1, Community *obj2)被解释为^void (Community *obj1, Community *obj2),而您必须包含正确的返回类型,即^NSComparisonResult (Community *obj1, Community *obj2)