这是我的API响应-
{"kitchen":"3","bath":"5","lanundry":"0","dining":"0","bedroom":"0"}
我已经将其加载到
NSDictionary
中,并且可以使用以下键检索值:NSDictionary *pdata = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error:nil];
[pdata objectForKey:@"dining"]
我想将
dictionary
对象添加到NSMutableArray
中,但是即使添加了五个记录,它也会用最后一个覆盖所有数组值。itemsA=[[NSMutableArray alloc] init];
imgCount *img=[[imgCount alloc] init];
if([pdata objectForKey:@"kitchen"])
{
[img setCount:[pdata objectForKey:@"kitchen"]];
[img setDesc:@"Kitchen"];
[itemsA addObject:img];
}
if([pdata objectForKey:@"bath"])
{
[img setCount:[pdata objectForKey:@"bath"]];
[img setDesc:@"Bathroom"];
[itemsA addObject:img];
}
if([pdata objectForKey:@"lanundry"])
{
[img setCount:[pdata objectForKey:@"lanundry"]];
[img setDesc:@"Laundry"];
[itemsA addObject:img];
}
if([pdata objectForKey:@"dining"])
{
[img setCount:[pdata objectForKey:@"kitchen"]];
[img setDesc:@"Kitchen"];
[itemsA addObject:img];
}
if([pdata objectForKey:@"bedroom"])
{
[img setCount:[pdata objectForKey:@"bedroom"]];
[img setDesc:@"Bedroom"];
[itemsA addObject:img];
}
我的表格视图显示5个行的最后一个值-
Bedroom (0)
但是我想要这样的结果
{"desc":"bathroom","count":"0"}, {"desc":"dining","count":"3"}
最佳答案
代码的问题是,您仅创建一个img
对象并重新使用它。由于所有对象都是通过Objective-C
中的引用访问的,因此您需要在所有if条件下创建单独的img
对象。尝试这个
itemsA=[[NSMutableArray alloc] init];
if([pdata objectForKey:@"kitchen"])
{
imgCount *img=[[imgCount alloc] init];
[img setCount:[pdata objectForKey:@"kitchen"]];
[img setDesc:@"Kitchen"];
[itemsA addObject:img];
}
if([pdata objectForKey:@"bath"])
{
imgCount *img=[[imgCount alloc] init];
[img setCount:[pdata objectForKey:@"bath"]];
[img setDesc:@"Bathroom"];
[itemsA addObject:img];
}
if([pdata objectForKey:@"lanundry"])
{
imgCount *img=[[imgCount alloc] init];
[img setCount:[pdata objectForKey:@"lanundry"]];
[img setDesc:@"Laundry"];
[itemsA addObject:img];
}
if([pdata objectForKey:@"dining"])
{
imgCount *img=[[imgCount alloc] init];
[img setCount:[pdata objectForKey:@"kitchen"]];
[img setDesc:@"Kitchen"];
[itemsA addObject:img];
}
if([pdata objectForKey:@"bedroom"])
{
imgCount *img=[[imgCount alloc] init];
[img setCount:[pdata objectForKey:@"bedroom"]];
[img setDesc:@"Bedroom"];
[itemsA addObject:img];
}
关于ios - NSDictionary到NSMutableArray,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39220611/