Sorting an NSSet

    //Sort a set

    NSSet *set = [[NSSet alloc] initWithArray:@[@(7), @(4), @(5), @(3), @(9), @(15)]];

    //Ascending

    NSArray *sorted = [set sortedArrayUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey:nil ascending:YES]]];

    NSLog(@"%@" , sorted);

    sorted = [set sortedArrayUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey:nil ascending:YES selector:@selector(compare:)]]];

    NSLog(@"%@" , sorted);

    sorted = [set sortedArrayUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey:nil ascending:YES comparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {

        return [obj1 compare:obj2];

    }]]];

    NSLog(@"%@" , sorted);



    //Descending

    sorted = [set sortedArrayUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey:nil ascending:NO]]];

    NSLog(@"%@" , sorted);

    sorted = [set sortedArrayUsingDescriptors:@[[[[NSSortDescriptor alloc] initWithKey:nil ascending:YES comparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {

        return [obj1 compare:obj2];

    }] reversedSortDescriptor]]];

    NSLog(@"%@" , sorted);

    sorted = [set sortedArrayUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey:nil ascending:YES comparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {

        return [obj2 compare:obj1];

    }]]];

    NSLog(@"%@" , sorted);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s