在表视图控制器中显示之前对JSON响应进行排序 - 目标C.

时间:2015-11-24 07:17:30

标签: ios objective-c iphone json

Rewards =     (
                {
            "Restaurant_ID" = 34;
            "Rewarded_Points" = 40;
            "Rewarded_Time" = "2015-11-23 09:16:00";
        },

           {
            "Restaurant_ID" = 40;
            "Rewarded_Points" = 60;
            "Rewarded_Time" = "2015-11-24 12:22:56";
          },
            {
            "Restaurant_ID" = 34;
            "Rewarded_Points" = 40;
            "Rewarded_Time" = "2015-11-24 12:22:56";
        }
);

我正在检索上面对变量的响应,并使用for循环

在TableViewController中显示
for(int i=0;i<rewards.count;i++){
        NSDictionary * rewardsObj = [rewards objectAtIndex:i];
        restId = [rewardsObj objectForKey:@"Restaurant_ID"];
        rewardedPoints = [rewardsObj objectForKey:@"Rewarded_Points"];
}
[self.tableView reloadData];

当前输出一次又一次显示相同的餐厅ID。我想如果有匹配的ID那么这些点需要计算总和。

34 - Total Points : 40

40 - Total Points : 60

34 - Total Points : 40 //再次

但我想按下面的方式排序

34 - Total Points : 80 // 40 + 40

40 - Total Points : 60

1 个答案:

答案 0 :(得分:2)

使用NSSortDescriptor作为您的概念,

步骤-1

最初选择基于排序的密钥,我们采用的是Rewarded_Points,并按ascending顺序排序。

NSSortDescriptor * Rewarded_Points =
[[NSSortDescriptor alloc] initWithKey:@"Rewarded_Points"
                           ascending:YES];
NSArray *descriptors = [NSArray arrayWithObjects:Rewarded_Points, nil];

 NSArray *sortedArrayOfDictionaries = [Rewards sortedArrayUsingDescriptors:descriptors]; // Rewards -> array of dictionary name

NSLog(@"final Value : %@", sortedArrayOfDictionaries);

其他Tutorial