我有一个名为Receipt
的自定义类。它具有另一个名为Retailer
的类的属性。 Retailer
有另一个名为retailerName
的属性。
我得到了一组Receipt
个对象。我希望它被排序为NSDictionary
,其键将是字母,值将是Receipt
的数组Retailer
对象的retailerName
以字母开头并且数组按字母顺序排序。
我有什么:
[
{
"retailerName": "Adidas",
"totalCost": 392.1,
"purchasedOn": 1461218024549
},
{
"retailerName": "Book My Show",
"totalCost": 392.1,
"purchasedOn": 1461218024549
},
{
"retailerName": "Albert-Heijn",
"totalCost": 392.1,
"purchasedOn": 1461218024549
},
{
"retailerName": "Amazon",
"totalCost": 392.1,
"purchasedOn": 1461218024549
},
{
"retailerName": "BlackBerry",
"totalCost": 392.1,
"purchasedOn": 1461218024549
},
{
"retailerName": "Lambhorgini",
"totalCost": 392.1,
"purchasedOn": 1461218024549
},
{
"retailerName": "Lewis Outlet",
"totalCost": 392.1,
"purchasedOn": 1461218024549
},
{
"retailerName": "Boston Store",
"totalCost": 392.1,
"purchasedOn": 1461218024549
},
{
"retailerName": "Lidl",
"totalCost": 392.1,
"purchasedOn": 1461218024549
}
]
我需要的是什么:
{
"A": [
{
"retailerName": "Adidas",
"totalCost": 392.1,
"purchasedOn": 1461218024549
},
{
"retailerName": "Albert-Heijn",
"totalCost": 392.1,
"purchasedOn": 1461218024549
},
{
"retailerName": "Amazon",
"totalCost": 392.1,
"purchasedOn": 1461218024549
}
],
"B": [
{
"retailerName": "BlackBerry",
"totalCost": 392.1,
"purchasedOn": 1461218024549
},
{
"retailerName": "Book My Show",
"totalCost": 392.1,
"purchasedOn": 1461218024549
},
{
"retailerName": "Boston Store",
"totalCost": 392.1,
"purchasedOn": 1461218024549
}
],
"L": [
{
"retailerName": "Lambhorgini",
"totalCost": 392.1,
"purchasedOn": 1461218024549
},
{
"retailerName": "Lewis Outlet",
"totalCost": 392.1,
"purchasedOn": 1461218024549
},
{
"retailerName": "Lidl",
"totalCost": 392.1,
"purchasedOn": 1461218024549
}
]
}
我知道这种情况并不复杂,但我尽力解释。如果需要,请询问进一步的解释。
提前致谢。
答案 0 :(得分:1)
我解决了我的问题:
这是我做的:
@implementation NSMutableDictionary (DictionaryForSectionIndex)
+(NSMutableDictionary *)createDictionaryForSectionIndex:(NSArray *)array
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (char firstChar = 'a'; firstChar <= 'z'; firstChar++)
{
//NSPredicates are fast
NSString *firstCharacter = [NSString stringWithFormat:@"%c", firstChar];
NSArray *content = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"retailerName beginswith[cd] %@", firstCharacter]];
NSMutableArray *mutableContent = [NSMutableArray arrayWithArray:content];
if ([mutableContent count] > 0)
{
NSString *key = [firstCharacter uppercaseString];
[dict setObject:mutableContent forKey:key];
}
}
return dict;
}
@end
答案 1 :(得分:0)
Array = [Array
sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
{
NSNumber *number1 = [NSNumber
numberWithFloat:[someValue floatValue]];
NSNumber *number2 = [NSNumber
numberWithFloat:[[somevalue floatValue]];
return [number2 compare:number1];
}];
您可以选择字典中的特定键并尝试对其进行排序