[英]How to turn NSArray of NSDictionarys into a nested NSArray of NSDictionarys
如果我有一個帶有幾個字典對象(每個字典都是一個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 }
]
]
您可以使用鍵值編碼和謂詞來做一些漂亮的事情。
//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]];
}
只要字典具有@"surname"
鍵或Person
對象具有-(NSString *)surname
方法,這將適用於Person
對象(更好)或詞典。
您應該使用專門的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]];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.