首先按“最近距离”排序两个NSMutableArray

时间:2012-10-02 16:08:22

标签: iphone objective-c ios xcode nssortdescriptor

我有两个数组,都是这样的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 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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];
}

答案 2 :(得分: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];

答案 3 :(得分: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]];
}