NSMutableArray排序返回错误的顺序

时间:2012-10-08 20:07:42

标签: objective-c ios sorting comparison nsmutablearray

我试图根据两个位置之间的距离(当前位置和第一个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];

    }

}

1 个答案:

答案 0 :(得分:3)

看起来你需要按venue.location.distance排序:

[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"]];

}];