我有一系列自定义对象。对象包括字典。 像这样:
CustomDataModel *dataModel;
dataModel.NSString
dataModel.NSDictionary
dataModel.image
我想按字典中的一个对象排序:
dataModel.NSDictionary ObjectWithkey=@"Name"
dataModel被加载到NSArray中。我现在想要按字典中的@“Name”键进行排序。这是NSSortDescriptor可以处理的吗?基本排序工作正常,只是还没有想出这个......
答案 0 :(得分: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];
}
答案 1 :(得分: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]];
上述方法适用于包含字典的数组