可能是一个noob问题:我正在尝试对nsmutablearray进行排序,但不知何故,订单没有被存储。
typedef struct {
float distance;
int index;
} DistanceAndIndex;
i = 0;
NSMutableArray *orderedDistances = [NSMutableArray arrayWithCapacity:(self.wayPoints.count)];
CLLocation* rwp2 = [[CLLocation alloc] initWithLatitude:52.080752 longitude:4.7527251];
latLonToEcef(rwp2.coordinate.latitude, rwp2.coordinate.longitude, 0.0, &myX, &myY, &myZ);
for (routeWayPoint *rwp in [[self wayPoints] objectEnumerator]) {
double poiX, poiY, poiZ, e, n, u;
latLonToEcef(rwp.location.coordinate.latitude, rwp.location.coordinate.longitude, 0.0, &poiX, &poiY, &poiZ);
ecefToEnu(rwp2.coordinate.latitude, rwp2.coordinate.longitude, myX, myY, myZ, poiX, poiY, poiZ, &e, &n, &u);
DistanceAndIndex distanceAndIndex;
distanceAndIndex.distance = sqrtf(n*n + e*e);
distanceAndIndex.index = i;
NSLog(@"Index = %i, %f", i, distanceAndIndex.distance);
[orderedDistances insertObject:[NSData dataWithBytes:&distanceAndIndex length:sizeof(distanceAndIndex)] atIndex:i++];
}
i=0;
[orderedDistances sortUsingComparator:(NSComparator)^(NSData *a, NSData *b) {
const DistanceAndIndex *aData = (const DistanceAndIndex *)a.bytes;
const DistanceAndIndex *bData = (const DistanceAndIndex *)b.bytes;
if (aData->distance < bData->distance) {
return NSOrderedAscending;
} else if (aData->distance > bData->distance) {
return NSOrderedAscending;
} else {
return NSOrderedSame;
}
}];
for (NSData *d in [orderedDistances reverseObjectEnumerator]) {
const DistanceAndIndex *distanceAndIndex = (const DistanceAndIndex *)d.bytes;
NSLog(@"item: %i, %f", distanceAndIndex->index, distanceAndIndex->distance);
}
输出如下:
[2021:907]航点:8 [2021:907]指数= 0,230.078827
[2021:907]指数= 1,171.626389
[2021:907]指数= 2,36.015743
[2021:907]指数= 3,103.174805
[2021:907]指数= 4,238.837616
[2021:907]指数= 5,278.074371
[2021:907]指数= 6,288.319763
[2021:907]指数= 7,321.953156
[2021:907] item:7,321.953156
[2021:907] item:6,288.319763
[2021:907] item:5,278.074371
[2021:907] item:4,238.837616
[2021:907] item:3,103.174805
[2021:907] item:2,36.015743
[2021:907] item:1,171.626389
[2021:907] item:0,230.078827
数组尚未重新排序(例如,在查看项目1,2和3时)。我觉得我忽略了一些非常基本的东西。有什么想法吗?
谢谢!
答案 0 :(得分:3)
你似乎忽略了这个错字:
if (aData->distance < bData->distance) {
return NSOrderedAscending;
} else if (aData->distance > bData->distance) {
return NSOrderedAscending;
} else {
return NSOrderedSame;
}
我认为第二个应该是NSOrderedDescending
。
答案 1 :(得分:1)
您似乎有两个if语句都返回NSOrderedAscending