0

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?

iceChao
  • 7
  • 5

2 Answers2

0

I think it's because you're using strings and not numbers. When sorting strings, 10 comes before 8 because it starts with a 1.

dudeman
  • 1,106
  • 8
  • 19
  • I fellow your idea and change my array to this NSArray *data = @[@[@1,@2,@3], @[@2,@3,@4,@5,@6], @[@8,@9,@10], @[@15,@16,@17,@18]]; the output is not correct..... – iceChao Sep 10 '15 at 01:44
0

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]];
tuledev
  • 10,177
  • 4
  • 29
  • 49
  • Thank you anhtu.Your answer is right.By the way,when I tried to init my array in this way data = @[@[@1,@2,@3].....] or this way data = @[@[@[nsnumber numberwithint:1],@[nsnumber numberwithint:2]...]]..I still couldnt get a right anwser.Do you know why? – iceChao Sep 10 '15 at 02:24
  • I think it sorts NSNumber like an object(maybe like string, I'm not sure), it doesn't get intValue of NSNumber. Because it can't know NSNumber is char, float, int or ... – tuledev Sep 10 '15 at 02:29