Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to sort an NSArray of NSDictionary objects?

I'm struggling with trying to sort an array of dictionaries.

My dictionaries have a couple of values of interest, price, popularity etc.

Any suggestions?

like image 979
iOSDevil Avatar asked Mar 06 '10 17:03

iOSDevil


People also ask

Can NSArray contain nil?

arrays can't contain nil.

How do you declare NSArray in Objective-C?

In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method. id objects[] = { someObject, @"Hello, World!", @42 }; NSUInteger count = sizeof(objects) / sizeof(id); NSArray *array = [NSArray arrayWithObjects:objects count:count];

What is NSDictionary?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.


2 Answers

Use NSSortDescriptor like this..

NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest" ascending:YES]; stories = [stories sortedArrayUsingDescriptors:@[descriptor]]; recent = [stories copy]; 

stories is the array you want to sort. recent is another mutable array which has sorted dictionary values. Change the @"interest" with the key value on which you have to sort.

All the best

like image 100
Warrior Avatar answered Sep 21 '22 11:09

Warrior


[array sortUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]]; 

I don't really want to break it into multiple lines. It's already simple enough for me.

like image 40
superarts.org Avatar answered Sep 24 '22 11:09

superarts.org