0

我想从带有键值对的 for 循环中向 NSMutabledictionary 添加值?

目前正在使用此代码

for(int j=0;j<[array count];j++){
    for(int l=0;l<array2 count] ;l++){   
          // retreive the category from plist ,then check whether its matching with "catid"
          NSString *temp=[NSString stringWithFormat:@"%@",allBookPlist[@"listbook"][j][@"cate"][l][@"categories"]];

           if([catId isEqualToString:temp]){    
                 // "catid" is matching with temp then ,retreive the corresponding bid from plist
                 NSString *str=[NSString stringWithFormat:@"%@",allBookPlist[@"listbook"][j][@"bid"]];
                 // add that  value "bid" and key "catid" to a mutabledictionary
                 NSMutableDictionary *m=[[NSMutableDictionary alloc]init];
                 [m setValue:str forKey:catId];
            }
     }
}

结果是每次最终字典“m”的值被最新值替换时,但我希望所有值都在一起?

在此处输入图像描述我试图获得这样的输出

4

3 回答 3

2

我想您可以将字典的初始化移到for之外,因为在for中它在每个循环中都被初始化了,这就是为什么它只有一个值

NSMutableDictionary *m = [[NSMutableDictionary alloc] init];
for(int j=0; j < [array count]; j++)
{
    NSMutableArray *containerArray = [[NSMutableArray alloc] init];
    for(int l=0;l<[array2 count] ;l++)
    {
        // retreive the category from plist ,then check whether its matching with "catid"
        NSString *temp=[NSString stringWithFormat:@"%@",allBookPlist[@"listbook"][j][@"cate"][l][@"categories"]];

        if([catId isEqualToString:temp])
        {
            // "catid" is matching with temp then ,retreive the corresponding bid from plist
            NSString *str=[NSString stringWithFormat:@"%@",allBookPlist[@"listbook"][j][@"bid"]];

            // add that  value "bid" and key "catid" to a mutabledictionary
             [containerArray addObject:str];
        }
        [m setValue:containerArray forKey:catId];
    }
}

更新

我已经更新了上面的代码,以便在图片中调整您的输出

于 2013-04-09T06:10:30.563 回答
0

试试这个代码。

NSMutableDictionary *m=[[NSMutableDictionary alloc]init];
for(int j=0;j<[array count];j++)
{
    for(int l=0;l<array2 count] ;l++)
    {
        // retreive the category from plist ,then check whether its matching with "catid"
        NSString *temp=[NSString stringWithFormat:@"%@",allBookPlist[@"listbook"][j][@"cate"][l][@"categories"]];
        if([catId isEqualToString:temp])
        {
            // "catid" is matching with temp then ,retreive the corresponding bid from plist
            NSString *str=[NSString stringWithFormat:@"%@",allBookPlist[@"listbook"][j][@"bid"]];
            // add that  value "bid" and key "catid" to a mutabledictionary
            [m setValue:str forKey:catId];
        }
    }

我认为您每次都在循环内分配一个新字典,这不是必需的。分配一次,然后继续向该可变字典添加值。

我想,每次你都有不同catId的 KEY

于 2013-04-09T06:07:56.533 回答
0

在你的循环中,请尝试这个逻辑

NSObject *collectionIndexString = indexPath;
NSMutableDictionary *tempDict = [myNSMutableArray[row] mutableCopy];
tempDict[@"collectionIndex"] = collectionIndexString;// Setting Key and Value
[myNSMutableArray replaceObjectAtIndex:row withObject:tempDict];
于 2016-07-26T19:57:05.453 回答