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?
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.
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]];
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With