如果我有一个带有多个字典对象的NSArray(或可变数组)(每个字典都是Person),就像这样:
[
{ forename: chris, surname: smith, age: 22 }
{ forename: paul, surname: smith, age: 24 }
{ forename: dave, surname: jones, age: 21 }
{ forename: alan, surname: jones, age: 26 }
{ forename: cecil, surname: reeves, age: 32 }
{ forename: pablo, surname: sanchez, age: 42 }
]
我如何将它分成四个数组的数组,按姓氏(并在该名字中)排序,如下所示:
[
[
{ forename: alan, surname: jones, age: 26 }
{ forename: dave, surname: jones, age: 21 }
]
[
{ forename: cecil, surname: reeves, age: 32 }
]
[
{ forename: pablo, surname: sanchez, age: 42 }
]
[
{ forename: chris, surname: smith, age: 22 }
{ forename: paul, surname: smith, age: 24 }
]
]
答案 0 :(得分:6)
你可以使用键值编码和谓词来做一些非常整洁的东西......
//retrieve an array of the distinct surnames
NSArray * distinctSurnames = [peopleArray valueForKeyPath:@"@distinctUnionOfObjects.surname"];
//at this point, if you need the surnames in a specific order, you can do so here.
NSMutableArray * groupedPeople = [NSMutableArray array];
//for each of the surnames...
for (NSString * surname in distinctSurnames) {
//create a predicate to only find people with this surname
NSPredicate * filter = [NSPredicate predicateWithFormat:@"surname = %@", surname];
//retrieve only the people with this surname and add them to the final array
[groupedPeople addObject:[peopleArray filteredArrayUsingPredicate:filter]];
}
这适用于Person
对象(可能更好)或字典,只要字典有@"surname"
键或Person
对象有{{1方法。
答案 1 :(得分:2)
您应该使用专门的Person类,而不是NSDictionary。
您可以先将其分组到词典数组字典中,例如
NSMutableDictionary* result = [NSMutableDictionary dictionary];
for (Person* person in peopleArray) {
NSString* surname = person.surname;
NSMutableArray* surnameArray = [result objectForKey:surname];
if (surnameArray == nil) {
[result setObject:[NSMutableArray arrayWithObject:person]
forKey:surname];
} else {
[surnameArray addObject:person];
}
}
return result;
如果你真的需要一个数组,你可以使用[result allValues]
。
如果您需要排序数组,则需要手动对其进行排序:
NSArray* sortedSurnames = [[result allKeys] sortedArrayUsingSelector:@selector(compare:)];
return [result objectsForKeys:sortedSurnames notFoundMarker:[NSNull null]];