我是iOS开发的新手。我正在使用Title,Count,Score创建NSMutableDictionary。现在我想用降序中的Count基础对我的NSMutableDictionary进行排序。请帮帮我。
self.top3_Question_Array = [[NSMutableArray alloc] init];
NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
[item setValue: [NSString stringWithFormat: itemName] forKey:@"Title"];
[item setValue: [NSNumber numberWithInteger: itemCount] forKey:@"Count"];
[item setValue: [NSNumber numberWithFloat: itemScore] forKey:@"Score"];
[self.top3_Question_Array addObject: item1];
答案 0 :(得分:1)
我尝试了以下编码。我的工作正常
NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
[item setValue:[NSString stringWithFormat: itemName] forKey:@"Title"];
[item setValue: [NSNumber numberWithInteger: itemCount] forKey:@"Count"];
[item setValue: [NSNumber numberWithFloat: itemScore] forKey:@"Score"];
[top3_Question_Array addObject:item];
NSSortDescriptor *countDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Count" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObjects:countDescriptor, nil];
NSArray *sortedArrayOfDictionaries = [top3_Question_Array sortedArrayUsingDescriptors:descriptors];
NSLog(@"sorted array of dictionaries: %@", sortedArrayOfDictionaries);
预期的输出也是
sorted array of dictionaries: (
{
Count = 2;
Score = 30;
Title = Cholate;
}
)
答案 1 :(得分:0)
试试此代码
NSArray *myArray = @[@{@"Title" : @"Hello", @"Count":@"3", @"Score":@"100"}, @{@"Title" : @"Hello", @"Count":@"2", @"Score":@"100"}, @{@"Title" : @"Hello", @"Count":@"1", @"Score":@"100"}, @{@"Title" : @"Hello", @"Count":@"4", @"Score":@"100"}];
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"Count"
ascending:NO
selector:@selector(localizedCaseInsensitiveCompare:)];
NSArray *sorted_array = [myArray sortedArrayUsingDescriptors:@[descriptor]];
NSLog(@"sorted_array: %@", sorted_array);