objective-csortingnsmutableset

Objective-C:Get a Wrong Output and I don't Why when I sort NSMutableSet


I was sorting an nsmutableSet but I met a weird problem.

   NSArray *data = @[@[@"1",@"2",@"3"],
                   @[@"2",@"3",@"4",@"5",@"6"],
                   @[@"8",@"9",@"10"],
                   @[@"15",@"16",@"17",@"18"]];

NSArray *sortArr = [[NSArray alloc] init];
NSMutableArray *Data = [[NSMutableArray alloc] init];

NSMutableSet *interSection = [[NSMutableSet alloc] init];
interSection = [NSMutableSet setWithArray:[data objectAtIndex:0]];

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES ];

for (int i =1; i < 4; i ++) {
    if ([interSection intersectsSet:[NSSet setWithArray:[data objectAtIndex:i]]]) {
        [interSection unionSet:[NSSet setWithArray:[data objectAtIndex:i]]];
    }
    else{

        sortArr = [interSection sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
        [Data addObject:sortArr];
        interSection = [NSMutableSet setWithArray:[data objectAtIndex:i]];

    }
}

if ([interSection count] != 0) {

    sortArr = [interSection sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
    [Data addObject:sortArr];
}
NSLog(@"%@",Data);

but the output is : ( 1, 2, 3, 4, 5, 6 ), ( 10, 8, 9 ), ( 15, 16, 17, 18 ) )

why it is(10,8,9) but (8,9,10) ?

Anyone knows the answer?


Solution

  • You're using NSSortDescriptor for string so it it sorts in string way (8>10, 9>10). You should create a custom NSSortDescriptor like this:

    NSSortDescriptor * sort = [NSSortDescriptor sortDescriptorWithKey:@"sort" ascending:YES comparator:^(id obj1, id obj2) {
    
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    sortArr = [[data objectAtIndex:i] sortedArrayUsingDescriptors:[NSArray arrayWithObject: sort]];