如何将 NSDictionarys 的 NSArray 变成 NSDictionarys 的嵌套 NSArray
Posted
技术标签:
【中文标题】如何将 NSDictionarys 的 NSArray 变成 NSDictionarys 的嵌套 NSArray【英文标题】:How to turn NSArray of NSDictionarys into a nested NSArray of NSDictionarys 【发布时间】:2010-10-21 17:51:29 【问题描述】:如果我有一个包含多个字典对象(每个字典都是一个 Person)的 NSArray(或可变数组),如下所示:
[
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
]
]
【问题讨论】:
【参考方案1】:您可以使用键值编码和谓词做一些非常简洁的事情...
//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
对象具有 -(NSString *)surname
方法。
【讨论】:
很棒的解决方案!没有足够的人使用 KVC。真的很漂亮。【参考方案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]];
【讨论】:
以上是关于如何将 NSDictionarys 的 NSArray 变成 NSDictionarys 的嵌套 NSArray的主要内容,如果未能解决你的问题,请参考以下文章
计算 NSArray 中 NSDictionarys 中的值