1

我有两个数组,都充满了这样的 NSString 对象:

NSMutableArray *titles = [[NSMutableArray alloc] initWithObjects:@"Title1", @"Title2", @"Title3", @"Title4", @"Title5", nil];

NSMutableArray *distances = [[NSMutableArray alloc] initWithObjects:@"139.45", @"23.78", @"347.82", @"10.29", @"8.29", nil];

如何首先按最近的距离对两个数组进行排序?

所以结果会是这样的:

titles = @"Title5", @"Title4", @"Title2", @"Title1", @"Title3"
distances = @"8.29", @"10.29", @"23.78", @"139.45", @"347.82"

我知道 NSSortDescriptor 可以在这些情况下使用,但是在查看文档后,我仍然不确定如何使用。

4

4 回答 4

1

您可以使用 NSComparator 块并使用 NSArray 的 sortedArrayUsingComparator 方法。在该块上,您将收到两个要比较的对象,根据比较结果,您可以使用 NSMutableArray exchangeObjectAtIndex:withObjectAtIndex: 方法更改标题的值。

于 2012-10-02T16:16:26.450 回答
1

我会以这种方式对距离进行排序......

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];

NSArray *sortedDistances = [listItem sortedArrayUsingComparator: ^(id a, id b) {
    NSNumber *aNum = [f numberFromString:a];
    NSNumber *bNum = [f numberFromString:b];
    return [aNum compare:bNum];
}];

我想不出一种特别快速的方法来对相关标题进行排序,但这应该可以......

NSMutableArray *sortedTitles = [NSMutableArray array];
NSDictionary *distanceTitle = [NSDictionary dictionaryWithObjects:titles forKeys:distances];

for (NSString *distance in sortedDistances) {
    NSString *associatedTitle = [distanceTitle valueForKey:distance];
    [sortedTitles addObject:associatedTitle];
}
于 2012-10-02T16:27:09.503 回答
0

这是我如何按距离值对字典数组进行排序的示例:

    -(void)reorderByDistance {
    NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:@"distance" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
    self.contentArray = [self.contentArray sortedArrayUsingDescriptors:sortDescriptors];
}

我的字典是这样的:

    NSDictionary *dict1 = [[NSDictionary alloc] initWithObjectsAndKeys:@"1", @"id", @"Business #1", @"name", @"This business does some pretty remarkable things", @"description", @"Alley Bar", @"category", @"1.2", @"distance", nil];
于 2012-10-02T16:16:00.317 回答
0

一种方法是创建一个字典,将标题映射到距离,对距离进行排序,然后遍历距离以重新创建标题:

NSMutableArray *titles = [[NSMutableArray alloc] initWithObjects:@"Title1", @"Title2", @"Title3", @"Title4", @"Title5", nil];

NSMutableArray *distances = [[NSMutableArray alloc] initWithObjects:@"139.45", @"23.78", @"347.82", @"10.29", @"8.29", nil];

//Create a map of current titles to distances
NSDictionary *titleDistanceMap = [NSDictionary dictionaryWithObjects:titles forKeys:distances];

//Need to sort the strings as numerical values
[distances sortUsingComparator:^(NSString *obj1, NSString *obj2) {

    return [obj1 compare:obj2 options:NSNumericSearch];
}];

//Now re-populate the titles array
[titles removeAllObjects];

for (NSString *distance in distances){
    [titles addObject:[titleDistanceMap objectForKey:distance]];
}
于 2012-10-02T16:56:56.523 回答