objective c - Sorting an nsmutable array --> order is not being saved? -
kind of noob question maybe: i'm trying sort nsmutablearray, somehow order not being stored.
typedef struct { float distance; int index; } distanceandindex; = 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); (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; } }]; (nsdata *d in [ordereddistances reverseobjectenumerator]) { const distanceandindex *distanceandindex = (const distanceandindex *)d.bytes; nslog(@"item: %i, %f", distanceandindex->index, distanceandindex->distance); }
the output following:
[2021:907] waypoints: 8 [2021:907] index = 0, 230.078827
[2021:907] index = 1, 171.626389
[2021:907] index = 2, 36.015743
[2021:907] index = 3, 103.174805
[2021:907] index = 4, 238.837616
[2021:907] index = 5, 278.074371
[2021:907] index = 6, 288.319763
[2021:907] index = 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
the array hasn't been reordered (for instance when looking @ items 1,2 , 3). feel i'm overlooking basic. ideas?
thanks!
you appear overlooking typo:
if (adata->distance < bdata->distance) { return nsorderedascending; } else if (adata->distance > bdata->distance) { return nsorderedascending; } else { return nsorderedsame; }
the second 1 should nsordereddescending
, think.
Comments
Post a Comment