Ios sort an array with dictionaries

I have an NSMutablearray filled with dictionaries [by JSON request]

I need to arrange an array depending on the key in dictionaries

dictionary

IdReward = 198; Name = "Online R d"; RewardImageUrl = "/FileStorimage=1206"; WinRewardPoints = 250; 

therefore the array consists of different dictionaries with the above form, and I need to organize a maximum to a minimum of WinRewardPoints

I saw this answer in SO, but I don’t understand yet how to accept it for my business,

Thank you very much!

+4
source share
2 answers
 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); 
+4
source
 // 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]; }]; 
+4
source

Source: https://habr.com/ru/post/1386013/


All Articles