Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help me sort NSMutableArray full of NSDictionary objects - Objective C

Tags:

objective-c

I have an NSMutableArray full of NSDictionary objects. Like so

NSMutableArray *names = [[NSMutableArray alloc] init];
for (NSString *string in pathsArray) {
    NSString *path = [NSString stringWithFormat:@"/usr/etc/%@",string];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:string,@"name",path,@"path",nil];
}

pathsArray is not sortable, so I'm stuck with the order of objects inside of it. I would like to sort the names array in alphabetical order of the objects for the key: @"name" in the dictionary. Can this be done easily or will it take several levels of enumeration?

EDIT: I Found the answer on SO in this question: Sort NSMutableArray

NSSortDescriptor class.

NSSortDescriptor *sortName = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[names sortUsingDescriptors:[NSArray arrayWithObject:sortName]];
[sortName release];

Anyone care to get some free answer points?

like image 621
Daddy Avatar asked Apr 23 '11 18:04

Daddy


People also ask

How do you sort an array of objects in Objective C?

The trick to sorting an array is a method on the array itself called "sortedArrayUsingDescriptors:". The method takes an array of NSSortDescriptor objects. These descriptors allow you to describe how your data should be sorted. So that handles the simple case, but what about if you want to sort your custom objects.

How do you sort an array of strings in Objective C?

For just sorting array of strings: sorted = [array sortedArrayUsingSelector:@selector(compare:)]; For sorting objects with key "name": NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(compare:)]; sorted = [array sortedArrayUsingDescriptors:@[sort]];

How do I create an NSDictionary in Objective C?

Creating NSDictionary Objects Using Dictionary Literals In addition to the provided initializers, such as init(objects:forKeys:) , you can create an NSDictionary object using a dictionary literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:forKeys:count:) method.

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.


1 Answers

Try something like this:

 NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"name"
                                          ascending:YES] autorelease];
 NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
 NSArray *sortedArray = [names sortedArrayUsingDescriptors:sortDescriptors];

 // names : the same name of the array you provided in your question.
like image 170
Ahmad Kayyali Avatar answered Sep 28 '22 08:09

Ahmad Kayyali