Reputation: 21760
I have an array of custom objects. The objects includes a dictionary. Something like this:
CustomDataModel *dataModel;
dataModel.NSString
dataModel.NSDictionary
dataModel.image
I'd like to sort by one of the objects in the dictionary:
dataModel.NSDictionary ObjectWithkey=@"Name"
The dataModel gets loaded into an NSArray. I now want to sort the by the @"Name" key in the dictionary. Is this something NSSortDescriptor can handle? Basic sort works fine, just haven't figured this one out yet...
Upvotes: 0
Views: 558
Reputation: 5302
//Sort an array which holds different dictionries - STRING BASED - Declare it in the .h
- (NSArray *)sortStringsBasedOnTheGivenField:(id)dictionaryKey arrayToSort:(NSMutableArray *)arrayToHoldTemp ascending:(BOOL)ascending {
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:dictionaryKey ascending:ascending selector:@selector(localizedCaseInsensitiveCompare:)] ;
NSArray *descriptors = [NSArray arrayWithObject:nameDescriptor];
[arrayToHoldTemp sortUsingDescriptors:descriptors];
[nameDescriptor release];
return arrayToHoldTemp;
}
Usage:
self.mainArrayForData = [NSArray arrayWithArray:[self sortNumbersBasedOnTheGivenField:@"Name" arrayToSort:arrayWhichContainsYourDictionries ascending:YES]];
the above method is good for an array that holds dictionaries
Upvotes: 0
Reputation: 24476
Your question isn't completely clear to me, but you can try something like this on your NSArray:
- (NSArray *)sortedItems:(NSArray*)items;
{
NSSortDescriptor *sortNameDescriptor =
[[[NSSortDescriptor alloc]
initWithKey:@"Name" ascending:NO]
autorelease];
NSArray *sortDescriptors =
[[[NSArray alloc]
initWithObjects:sortNameDescriptor, nil]
autorelease];
return [items sortedArrayUsingDescriptors:sortDescriptors];
}
Upvotes: 1