2015-09-10 58 views
0

我正在排序nsmutableSet,但我遇到了一個奇怪的問題。Objective-C:得到錯誤的輸出,我不爲什麼當我排序NSMutableSet

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

但輸出是: ( 1, 2, 3, 4, 5,) ( 10, 8,) ( 15, 16, 17,) )

爲什麼它是(10,8,9)但(8,9,10)?

任何人都知道答案?

回答

0

您對字符串使用NSSortDescriptor,因此它按字符串方式排序(8> 10,9> 10)。您應該創建一個自定義NSSortDescriptor這樣的:

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

謝謝anhtu.Your答案是正確的。順便說一下,當我試圖以這種方式初始化我的數組data = @ [@ [@ 1,@ 2,@ 3]。 ....]或這種方式data = @ [@ [@ [nsnumber numberwithint:1],@ [nsnumber numberwithint:2] ...]] ..我仍然無法得到一個正確的anwser.Do you know知道爲什麼? – iceChao

+0

我認爲它將NSNumber排序爲一個對象(可能像字符串,我不確定),它不會得到NSNumber的intValue。因爲它不知道NSNumber是char,float,int還是... – anhtu

+0

謝謝anhtu! – iceChao

0

我認爲這是因爲你使用字符串而不是數字。當對字符串進行排序時,10會在8之前,因爲它以1開頭。

+0

我老鄉你的想法和改變我的陣列來此的NSArray *數據= @ [@ [@ 1,@ 2,@ 3], @ [@ 2,@ 3,@ 4,@ 5,@ 6], @ [@ 8,@ 9,@ 10], @ [@ 15,@ 16,@ 17,@ 18]];輸出是不正確的..... – iceChao

相關問題