使用索引号数组对NSArray进行排序

时间:2016-04-01 10:38:02

标签: ios objective-c arrays

我有一个这样的数组:

NSArray *needSortedArray = @[@"Alex", @"Rachel", @"Mohamad"];

和像这样的索引数组:

NSArray *indexArray = @[@1, @0, @2];

所以我想要的输出看起来像这样:

needSortedArray = @[@"Rachel", @"Alex", @"Mohamad"];

我该怎么做?有可能吗?

2 个答案:

答案 0 :(得分:5)

试试这个:

    NSArray *unsortedArray = @[@"Alex", @"Rachel", @"Mohamad"];
    NSArray *indexArray = @[@1, @0, @2];

    NSMutableArray * sortedArray = [[NSMutableArray alloc] initWithCapacity:unsortedArray.count];
    for (NSNumber * num in indexArray)
    {
        [sortedArray addObject:[unsortedArray objectAtIndex:num.integerValue]];
    }

   //now sortedArray has sorted objects.

答案 1 :(得分:0)

支持任何类似索引类型的解决方案:

NSArray<NSString*> *unsortedArray = @[@"Alex", @"Rachel", @"Mohamad", @"Andrew"];
NSArray<NSNumber*> *indexArray = @[@1, @12, @23, @12];

NSParameterAssert([indexArray count] == [unsortedArray count]);
NSArray* sorted = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
    NSNumber* index1 = indexArray[[unsortedArray indexOfObjectIdenticalTo:obj1]];
    NSNumber* index2 = indexArray[[unsortedArray indexOfObjectIdenticalTo:obj2]];

    NSComparisonResult result = [index1 compare:index2];
    return result;
}];

NSLog(@"Sorted array: %@", sorted);