iPhone - Sorting of NSMutableArray containing NSDictionary with 2 keys

Hihi all,

I have an NSMutableArray containing various NSDictionary. In each of the NSDictionary, I have two key-value-pairs, eg: username and loginDate.

I would need to sort all NSDictionary in this NSMutableArray based on loginDate descending and username ascending.

Just to illustrate in more details:

NSMutableArray (index 0): NSDictionary -> username:"user1", loginDate:20 Dec 2011
NSMutableArray (index 1): NSDictionary -> username:"user2", loginDate:15 Dec 2011
NSMutableArray (index 2): NSDictionary -> username:"user3", loginDate:28 Dec 2011
NSMutableArray (index 3): NSDictionary -> username:"user4", loginDate:28 Dec 2011

After the sorting, the result in the array should be:

NSMutableArray (index 0): NSDictionary -> username:"user3", loginDate:28 Dec 2011
NSMutableArray (index 1): NSDictionary -> username:"user4", loginDate:28 Dec 2011
NSMutableArray (index 2): NSDictionary -> username:"user1", loginDate:20 Dec 2011
NSMutableArray (index 3): NSDictionary -> username:"user2", loginDate:15 Dec 2011

How can I achieve this? Have gone through some of the sortUsingComparator method, can't figure out a way for this.

Answers


Maybe something like this?

[array sortUsingDescriptors:
 [NSArray arrayWithObjects:
  [[[NSSortDescriptor alloc]
    initWithKey:@"loginDate"
    ascending:NO]
   autorelease],
  [[[NSSortDescriptor alloc]
    initWithKey:@"username"
    ascending:YES]
   autorelease],
  nil]];

If you build for iOS 4 or higher you can even do:

[array sortUsingDescriptors:
 [NSArray arrayWithObjects:
  [NSSortDescriptor sortDescriptorWithKey:@"loginDate" ascending:NO],
  [NSSortDescriptor sortDescriptorWithKey:@"username" ascending:YES],
  nil]];

This works using the compare: method to compare property key values, that is the value returned by valueForKey:. In the case of NSDictionary it will more or less just call objectForKey: to get the value. There are some special notations like prefixing key name with "@", see Difference valueforKey objectForKey for more details.


Need Your Help

How can I make Python program read line in file

python linux dictionary passwords crypt

I have 2 files, passwd and dictionary. The passwd is a test file with one word, while the dictionary has a list of a few lines of words. My program so far reads and compares only the first line of ...

Executing a lisp function from Java

java swing common-lisp sbcl

I have compiled Lisp code and I want to make a front end GUI for it. I chose Java swing to develop the GUI. Now I want to call the LISP code (SBCL) from java application! Is there any way to do th...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.