0

2 つの場所 (現在の場所、および最初の for ループで指定された座標) 間の距離に応じて NSMutableArray を並べ替えようとしています。ただし、並べ替えは特定の順序を返すのではなく、完全にランダムな順序を返します (ここの写真を参照してください: http://u.maxk.me/iz7Z )。

どこが間違っているのか教えてください。

並べ替え:

[self.venues sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {

    return [[obj1 objectForKey:@"distance"] compare:[obj2 objectForKey:@"distance"]];

}];

-setVenues:

- (void) setVenues:(NSMutableArray *)_venues {

    if (venues != _venues) {

        [venues release];

        ...

        NSMutableArray *updatedVenues = [NSMutableArray array];            

        for (NSDictionary *venue in _venues) {

            ...

            if (address != nil && city != nil) {

                CLLocationCoordinate2D coord = CLLocationCoordinate2DMake([[_location objectForKey:@"lat"] floatValue], [[_location objectForKey:@"lng"] floatValue]);

                CLLocation *currentLoc = [[CLLocation alloc] initWithLatitude:self.currentLocation.latitude longitude:self.currentLocation.longitude];
                CLLocation *venueLoc = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude];

                CLLocationDistance distance = [venueLoc distanceFromLocation:currentLoc];

                float miles = distance / 1000;
                miles *= 0.621371192; // metres to miles

                NSMutableDictionary *newLocation = [NSMutableDictionary dictionaryWithDictionary:_location];
                [newLocation removeObjectForKey:@"distance"];
                [newLocation setObject:[NSNumber numberWithFloat:miles] forKey:@"distance"];
                _location = [NSDictionary dictionaryWithDictionary:newLocation];

                ...

                NSMutableDictionary *newVenue = [NSMutableDictionary dictionaryWithDictionary:venue];
                [newVenue removeObjectForKey:@"location"];
                [newVenue setObject:_location forKey:@"location"];                   
                [updatedVenues addObject:newVenue];

            }

        }

        venues = [updatedVenues retain];

    }

}
4

1 に答える 1

3

会場.場所.距離で並べ替える必要があるようです:

[self.venues sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {

    NSNumber *distance1 = [[obj1 objectForKey:@"location"] objectForKey:@"distance"];
    NSNumber *distance2 = [[obj2 objectForKey:@"location"] objectForKey:@"distance"];
    return [distance1 compare:distance2];

}];

Xcode >= 4.4 (iOS の場合は 4.5) のバージョンを使用している場合は、次のように実行できます。

[self.venues sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [obj1[@"location"][@"distance"] compare:obj2[@"location"][@"distance"]];

}];
于 2012-10-08T20:57:38.347 に答える