Sorting an Array of custom objects by a dictionary included in the custom object: How?
-
13-09-2019 - |
Question
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...
Solution
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];
}
OTHER TIPS
//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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow