IPhone - NSMutableArray Sort containing an NSDictionary with 2 keys

Hello everybody,

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

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

Just to illustrate in more detail:

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 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? Passed through some sortUsingComparator method, I can’t figure out how to do this.

+6
source share
1 answer

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 are building 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 the values ​​of the property key, that is, the value returned by valueForKey: In the case of NSDictionary it will be more or less simple to call objectForKey: to get the value. There are special notations, such as the prefix key name with "@", see Difference Value for Key objectForKey for more details.

+6
source

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


All Articles