我是iOS新手,
我有一个NSdictionary的NSMutableArray,
我想要做所有相同键的总和, 这是我尝试但没有成功的代码
ARQProfileDataArray(这是NSMutableArray):
{
"type":"arqEquity",
"category":"Equity",
"investment":"6935.7",
"percentage":"25.43"
},
{
"type":"liquid",
"category":"MF",
"investment":0,
"percentage":0
},
{
"type":"balanced",
"category":"MF",
"investment":"10215.87",
"percentage":"37.46"
},
{
"type":"equityMF",
"category":"MF",
"investment":"10123.41",
"percentage":"37.12"
}
我希望将所有category
加上MF
以及所有category
加上Equity
我的代码:
NSNumber *sum = [ARQProfileDataArray valueForKeyPath:@"@sum.category"];
NSLog(@"sum---------- %@",sum);
我的代码在此行NSNumber *sum = [ARQProfileDataArray valueForKeyPath:@"@sum.category"];
请帮助我犯错的地方? 提前致谢!!
答案 0 :(得分:1)
使您的NSMutableArray循环。请检查Objective-C的语法及其长时间和时间。我没有检查过
screen -r tensroboard-screen
现在您在//Declare variable for category types
int mfCount = 0
int equityCount = 0
for dict in ARQProfileDataArray {
if ([dict[@"category"] isEqualToString:@"MF"]) {
mfCount += 1;
} else if ([dict[@"category"] isEqualToString:@"Equity"]) {
equityCount += 1;
}
}
中有一些类别。
如果您不想为每个键创建变量,那么您可以改为使用字典而不是在案件内部更新。
答案 1 :(得分:0)
请找一个简单而通用的解决方案。
NSMutableArray *sumArray = [@[@{
@"type":@"arqEquity",
@"category":@"Equity",
@"investment":@6935.7,
@"percentage":@"25.43"
},
@{
@"type":@"liquid",
@"category":@"MF",
@"investment":@0,
@"percentage":@0
},
@{
@"type":@"balanced",
@"category":@"MF",
@"investment":@10215.87,
@"percentage":@"37.46"
},
@{
@"type":@"equityMF",
@"category":@"MF",
@"investment":@10123.41,
@"percentage":@"37.12"
}] mutableCopy];
// It will work for Number and Integer.
NSNumber *sum = [sumArray valueForKeyPath:@"@sum.investment"];
NSLog(@"Sum of Investment : %@", sum);
NSArray *categorys = [sumArray valueForKeyPath:@"@distinctUnionOfObjects.category"];
for (NSString* item in categorys)
{
NSArray *categoryArray = [self findSameValueKey:sumArray WithKey:@"category" WithValue:item];
NSLog(@"%@ count: %@", item,@([categoryArray count]));
}
// Helps to find same value key.
-(NSArray*)findSameValueKey:(NSArray*)dateArray WithKey:(NSString*)key WithValue:(NSString*)value{
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(NSDictionary *resultsDictionary, NSDictionary *bind){
if ([resultsDictionary objectForKey: key] && [[resultsDictionary objectForKey: key] isEqualToString:value]) {
return true;
}
return false;
}];
// Apply the predicate block .
NSArray *sameValueKeys = [dateArray filteredArrayUsingPredicate:predicate];
return sameValueKeys;
}