0

可能是一个菜鸟问题:我正在尝试对一个 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] 项目:7, 321.953156

[2021:907] 项目:6, 288.319763

[2021:907] 项目:5, 278.074371

[2021:907] 项目:4, 238.837616

[2021:907] 项目:3, 103.174805

[2021:907] 项目:2, 36.015743

[2021:907] 项目:1, 171.626389

[2021:907] 项目:0, 230.078827

数组根本没有被重新排序(例如在查看项目 1,2 和 3 时)。我觉得我忽略了一些非常基本的东西。有任何想法吗?

谢谢!

4

2 回答 2

3

您似乎忽略了这个错字:

       if (aData->distance < bData->distance) {
            return NSOrderedAscending;
        } else if (aData->distance > bData->distance) {
            return NSOrderedAscending;
        } else {
            return NSOrderedSame;
        }

第二个应该是NSOrderedDescending,我想。

于 2013-08-19T20:59:23.140 回答
1

您似乎有两个 if 语句都返回 NSOrderedAscending

于 2013-08-19T21:02:02.230 回答