0

我有一组自定义对象。对象包括字典。像这样的东西:

CustomDataModel *dataModel;

dataModel.NSString
dataModel.NSDictionary
dataModel.image

我想按字典中的一个对象排序:

dataModel.NSDictionary ObjectWithkey=@"Name"

dataModel 被加载到一个 NSArray 中。我现在想按字典中的 @"Name" 键排序。这是 NSSortDescriptor 可以处理的吗?基本排序工作正常,只是还没有弄清楚这个......

4

2 回答 2

1

你的问题对我来说并不完全清楚,但你可以在你的 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];
}
于 2009-12-05T06:15:59.483 回答
0
//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;
    }

用法:

self.mainArrayForData = [NSArray arrayWithArray:[self sortNumbersBasedOnTheGivenField:@"Name" arrayToSort:arrayWhichContainsYourDictionries ascending:YES]];

上述方法适用于包含字典的数组

于 2010-10-28T06:26:16.227 回答