简体   繁体   中英

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?

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.

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]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM