0
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";
        }
);

im retrieving above response to variable and show in TableViewController using for loop

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

Current Output is showing same Restaurant ID again and again. i want if there is matching ID then those points need to be calculate sum.

34 - Total Points : 40

40 - Total Points : 60

34 - Total Points : 40 //Again

but i want to sort it like below

34 - Total Points : 80 // 40+40

40 - Total Points : 60

3
  • are u storing restId and rewardedPoints into array ? Commented Nov 24, 2015 at 7:21
  • @Venkat yes. if there is matching restId then rewarded points output sum of all of it. Commented Nov 24, 2015 at 7:23
  • u can create a dictionary with the key is the ID, then when parsing JSON to the dictionary, u can check if the key exist then do your SUM, else then make new pair, its the easiest and fastest way i can think of Commented Nov 24, 2015 at 8:36

1 Answer 1

2

use NSSortDescriptor for your concept,

Step -1

initially select the key based on sort , for ex Rewarded_Points we take , and sort as ascending order.

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

for additional Tutorial

Sign up to request clarification or add additional context in comments.

1 Comment

I submitted the partial answer, for your second query i have one doubt in here your date is differnet it is fine to add, else you try for omit the duplicate value based on keys...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.