Search code examples
iosobjective-cnsmutablearraynsarray

NSMutableArray sortedArrayUsingDescriptors: requires intermediate results array


sortedarrayusingdescriptors doesn't appear to do an in-place sort as I'd hoped. It looks like it requires an additional array with which to sort into, and then you would clear your original mutable array and repopulate it with the results of the sorted array.

For example, I expected this to work...

@interface SomeClass
{
   NSMutableArray *mutableArrayOfItems;
}

-(void)sortItems
    {
        NSSortDescriptor *descriptor1 = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES];
        NSSortDescriptor *descriptor2 = [[NSSortDescriptor alloc]initWithKey:@"age" ascending:NO];

        NSArray *descriptors = [NSArray arrayWithObjects:descriptor1,descriptor2, nil];
        mutableArrayOfItems = [mutableArrayOfItems sortedArrayUsingDescriptors:descriptors];
    }

But instead had to do this....

@interface SomeClass
{
   NSMutableArray *mutableArrayOfItems;
}

-(void)sortItems
    {
        NSSortDescriptor *descriptor1 = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES];
        NSSortDescriptor *descriptor2 = [[NSSortDescriptor alloc]initWithKey:@"age" ascending:NO];

        NSArray *descriptors = [NSArray arrayWithObjects:descriptor1,descriptor2, nil];
        NSArray *sortedArray = [mutableArrayOfItems sortedArrayUsingDescriptors:descriptors];
        [mutableArrayOfItems removeAllObjects];
        [mutableArrayOfItems addObjectsFromArray:sortedArray];
    }

Solution

  • That's because you use a method that creates a new array. What about calling sortUsingDescriptors: instead?