views:

157

answers:

2

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...

+1  A: 

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];
}
Matt Long
This is the solution I came up with as well, However, I wasn't sure it would work at first because of the NSDictionary. Anyways, Works like a charm! Thanks for the help and confirmation, Matt.
Jordan
A: 
//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

Mr H