我有一个NSMutablearray,由字典[来自JSON请求]填充
我需要根据词典中的键来组织数组
字典
IdReward = 198; Name = "Online R d"; RewardImageUrl = "/FileStorimage=1206"; WinRewardPoints = 250;
所以数组由不同的字典和上面的表格组成,我需要按最大值组织到最小WinRewardPoints
我在SO中看过this answer,但我还不了解如何采用它,
非常感谢!
答案 0 :(得分:4)
IdReward = 198;
Name = "Online R d";
RewardImageUrl = "/FileStorimage=1206";
WinRewardPoints = 250;
NSMutableArray *arr = [[NSMutableArray alloc]init];
for (int i=0; i<[dict count]; i++) {
[arr addObject:[dict valueForKey:@"WinRewardPoints"]];
}
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:nil ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
arr = [[arr sortedArrayUsingDescriptors:sortDescriptors] copy];
NSMutableArray *final_arr = [[NSMutableArray alloc]init];
for(NSString* str in arr)<p>
{
for(int i=0 ; i<[dict count]; i++)
{
<t>if ([str isEqualToString:[[dict valueForKey:@"WinRewardPoints"]objectAtIndex:i]])
{
[final_arr addObject:[dict objectAtIndex:i]];
}
}
}
NSLog(@"%@",final_arr);
答案 1 :(得分:4)
// create a NSString constant for the key we want to sort by, so we don't have to create more NSString instances while sorting
static NSString* const keyToSortBy = @"WinRewardPoints";
// sort an array that contains dictionaries, each of which contains a NSNumber for the key defined "WinRewardPoints"
[yourArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSNumber* n1 = [obj1 objectForKey:keyToSortBy];
NSNumber* n2 = [obj2 objectForKey:keyToSortBy];
return [n1 compare:n2];
}];