2013-07-31 44 views
0

NSMutableArray我想这样的排列来看:排序嵌套的NSMutableArray

(
     { 
      "title" = "Bags"; 
      "price" = "$200"; 
     }, 
     { 
      "title" = "Watches"; 
      "price" = "$40"; 
     }, 
     { 
      "title" = "Earrings"; 
      "price" = "$1000"; 
     } 
) 

这其中包含的NSMutableArray个集合的NSMutableArray。我想先按price排序,然后按title排序。

NSSortDescriptor *sortByPrices = [[NSSortDescriptor alloc] initWithKey:@"price" ascending:YES]; 
NSSortDescriptor *sortByTitle = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES]; 

[arrayProduct sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sortByPrices,sortByTitle,nil]]; 

但是,似乎没有工作,如何排序嵌套NSMutableArray

+0

它怎么没有工作,你之前和之后有什么,你是如何做的那种? – Wain

+1

它看起来像数组字典里面 – lupatus

回答

1

我想错误是price是一个字符串。因此,它不是数字比较,而是按字母顺序。尝试使用比较块排序的阵列和分析该块,而不是里面的价格:

[array sortUsingComparator:^(id _a, id _b) { 
    NSDictionary *a = _a, *b = _b; 

    // primary key is the price 
    int priceA = [[a[@"price"] substringFromIndex:1] intValue]; 
    int priceB = [[b[@"price"] substringFromIndex:1] intValue]; 

    if (priceA < priceB) 
     return NSOrderedAscending; 
    else if (priceA > priceB) 
     return NSOrderedDescending; 
    else // if the prices are the same, sort by name 
     return [a[@"title"] compare:b[@"title"]]; 
}]; 
5

尝试

NSMutableArray *arrayProducts = [@[@{@"price":@"$200",@"title":@"Bags"},@{@"price":@"$40",@"title":@"Watches"},@{@"price":@"$1000",@"title":@"Earrings"}] mutableCopy]; 

    NSSortDescriptor *priceDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"" 
                   ascending:YES 
                   comparator:^NSComparisonResult(NSDictionary *dict1, NSDictionary *dict2) { 
                    return [dict1[@"price"] compare:dict2[@"price"] options:NSNumericSearch]; 
    }]; 

    NSSortDescriptor *titleDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES]; 



    [arrayProducts sortUsingDescriptors:@[priceDescriptor,titleDescriptor]]; 

    NSLog(@"SortedArray : %@",arrayProducts); 
+0

NSArray * array – Desdenova

+0

@Desdenova谢谢,不知道它是如何被错过。直接从xcode复制。 – Anupdas

+0

'*'在'dict1'之前缺少 - >比较:^ NSComparisonResult(NSDictionary dict1,NSDictionary * dict2){ – EarlySun