Sort dictionaries in an array?

I need to sort nsmutablearray from nsdiction using a key object from a dictionary. NSNumber object. How would I sort dictionaries into nsmutablearray with the first object being the highest number n?

Thanks!

+2
source share
2 answers

Using a special comparator defined using block (you can go in other ways, but it's quite compact):

NSComparator mysort = ^(id dict1, id dict2) { NSNumber n1 = [dict1 objectForKey:@"key"]; NSNumber n2 = [dict2 objectForKey:@"key"]; return (NSComparisonResult)[n1 compare:n2]; }; [yourArray sortUsingComparator:mysort]; 
+5
source

This code seems a bit off. Here is what works.

 [theMutableArrayThatWillBeSorted sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { NSNumber* n1 = [obj1 objectForKey:@"key"]; NSNumber* n2 = [obj2 objectForKey:@"key"]; return [n1 compare:n2]; }]; 
+1
source

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


All Articles