将两个NSArrays并排排列在一起

我有几个数组需要并排sorting。

例如,第一个数组的名字是: @[@"Joe", @"Anna", @"Michael", @"Kim"] ,另一个数组保存地址: @[@"Hollywood bld", @"Some street 3", @"That other street", @"country road"] ,这些数组的指标汇集在一起​​。 “乔”住在“好莱坞”等等。

我想按字母顺序排列名称数组,然后将地址数组sorting在一起,所以他们仍然走在一起,“好莱坞”的索引与“乔”相同。 我知道如何按字母sorting一个数组

 NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:NO]; [myArray sortUsingDescriptors:[NSArray arrayWithObject:sort]]; 

但有没有简单的方法获得第二个数组使用适当的顺序sorting?

  1. 创build一个置换数组,初始设置为p[i]=i
  2. 根据第一个数组的name键对排列进行sorting
  3. 使用排列来重新排列这两个数组

例如:假设第一个数组是{"quick", "brown", "fox"} 。 置换以{0, 1, 2} {1, 2, 0}开始,sorting后变为{1, 2, 0} 。 现在你可以通过置换数组,并根据需要重新sorting原始数组和第二个数组。

 NSArray *first = [NSArray arrayWithObjects: @"quick", @"brown", @"fox", @"jumps", nil]; NSArray *second = [NSArray arrayWithObjects: @"jack", @"loves", @"my", @"sphinx", nil]; NSMutableArray *p = [NSMutableArray arrayWithCapacity:first.count]; for (NSUInteger i = 0 ; i != first.count ; i++) { [p addObject:[NSNumber numberWithInteger:i]]; } [p sortWithOptions:0 usingComparator:^NSComparisonResult(id obj1, id obj2) { // Modify this to use [first objectAtIndex:[obj1 intValue]].name property NSString *lhs = [first objectAtIndex:[obj1 intValue]]; // Same goes for the next line: use the name NSString *rhs = [first objectAtIndex:[obj2 intValue]]; return [lhs compare:rhs]; }]; NSMutableArray *sortedFirst = [NSMutableArray arrayWithCapacity:first.count]; NSMutableArray *sortedSecond = [NSMutableArray arrayWithCapacity:first.count]; [p enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSUInteger pos = [obj intValue]; [sortedFirst addObject:[first objectAtIndex:pos]]; [sortedSecond addObject:[second objectAtIndex:pos]]; }]; NSLog(@"%@", sortedFirst); NSLog(@"%@", sortedSecond); 

首先,您可能需要重新考虑一个架构,要求您以这种并行方式对两个数组进行sorting。 但是话虽如此,你可以通过创build一个临时的字典数组来保持两个数组的配对。

然后你sorting组合的数组,并再次提取两个数组,按要求sorting:

原始数据:

 NSArray *names = @[@"Joe", @"Anna", @"Michael"]; NSArray *addresses = @[@"Hollywood bld", @"Some street 3", @"That other street"]; 

实际的sorting代码:

 NSMutableArray *combined = [NSMutableArray array]; for (NSUInteger i = 0; i < names.count; i++) { [combined addObject: @{@"name" : names[i], @"address": addresses[i]}]; } [combined sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]]]; names = [combined valueForKey:@"name"]; addresses = [combined valueForKey:@"address"]; 

请注意, valueForKey:用于数组提取具有相同大小的新数组,并填充原始数组中的对象的属性。 在这种情况下,它会从原始数组中创build新的数组,按需要进行sorting。

这种方法只需要几行代码,如果需要的话,很容易跟踪和debugging。

最好的方法是重构数据,以便只有一个数组。 在你的例子中,创build一个名称和地址都是最有意义的,把它们放在一个数组中,并按名称sorting。

你也许可以通过跟踪sorting前后对象的索引来做到这一点,但也许有一个单一的对象具有所有这些属性

 Person : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *addresss; 

然后,将这些对象存储到单个数组中,您可以按nameaddress键path进行sorting