Search code examples
cocoa-touchcocoanssortdescriptornsorderedset

Sorting NSOrderedSet using NSSortDescriptor


When executing this code:

NSSortDescriptor *sortDescriptor = [Characteristic sortDescriptor];
[workingSet sortUsingComparator:[sortDescriptor comparator]];

I get this error:

*** -[NSMutableOrderedSet sortUsingComparator:]: comparator cannot be nil

sortDescriptor is non-nil, so I've no idea why this doesn't work.

I can work around the problem with the code below, which works perfectly:

NSSortDescriptor *sortDescriptor = [Characteristic sortDescriptor];
NSArray *workingArray = [[workingSet array] sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
workingSet = [NSMutableOrderedSet orderedSetWithArray:workingArray];

Solution

  • Check out the NSArray reference for the difference between the two methods

    A typical usage for the first method would be something like this

    NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {
    
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
    
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    

    (Example from Apple)

    Where as the second method would be more like:

    NSSortDescriptor *nameSort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:nameSort];
    
    NSArray *sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors];