gpt4 book ai didi

ios - NSDictionary 到 NSMutableArray

转载 作者:行者123 更新时间:2023-11-28 18:00:56 25 4
gpt4 key购买 nike

这是我的 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];
}

我的 TableView 显示 5 行,最后一个值 -

Bedroom (0)

但我想要这样的结果

{"desc":"bathroom","count":"0"}, {"desc":"dining","count":"3"}

最佳答案

为此,您可以这样尝试。首先获取字典的所有键,然后使用该键数组创建字典数组。

NSArray*keys=[dict allKeys];
NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSString *key in keys) {
NSDictionary *dic = @{ @"desc":key, @"count": [dict objectForKey:key] };
[array addObject:dic];
}
NSLog(@"Array - %@",array);

编辑:如果您想要自定义类对象,您可以这样尝试。

 for (NSString *key in keys) {
imgCount *imgObject=[[imgCount alloc] init];
[imgObject setCount:[pdata objectForKey:key]];
[imgObject setDesc:[key capitalizedString]];
[array addObject:imgObject];
}

关于ios - NSDictionary 到 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39220611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com