Sorting two NSArrays together side by side

前端 未结 4 785
一生所求
一生所求 2020-11-27 22:49

I have several arrays that need to be sorted side by side.

For example, the first array has names: @[@\"Joe\", @\"Anna\", @\"Michael\", @\"Kim\"], and a

4条回答
  •  孤街浪徒
    2020-11-27 23:38

    First off, you might want to re-consider an architecture that requires you to sort two arrays in a parallel fashion like this. But having said that, you can do it by creating a temporary array of dictionaries that keep the elements of the two arrays paired.

    Then you sort the combined array, and extract the two arrays again, sorted as requested:

    Original data:

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

    The actual sorting code:

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

    Notice that valueForKey: used on an array extracts a new array with the same size, populated with the properties of the objects in the original array. In this case, it create new arrays from the original ones, sorted as wanted.

    This approach only requires a few lines of code and is easy to follow and debug, if needed.

提交回复
热议问题