gpt4 book ai didi

ios - 如何在 iOS 中按索引将数组添加到数组中?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:19:28 25 4
gpt4 key购买 nike

我是 iOS 开发新手。我想将我的 JSON 解析数据字典数组键值添加到另一个数组中,但它只会将我的最后一个数组索引添加到新数组中。

我的代码就像

-(void)fetchedData:(NSData *)responsedata
{
if (responsedata.length > 0)
{
NSError* error;

self.json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[_json objectForKey:@"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[_json objectForKey:@"data"];
[self.imageArray addObjectsFromArray:arr];
[self.storeViewTable reloadData];
}
self.storeViewTable.hidden=FALSE;
}
NSMutableArray *imagearray=[[NSMutableArray alloc]init];
for (index=0; index <[self.imageArray count]; index ++)
{
for(NSDictionary *dict in self.imageArray )
{
imagearray = [dict valueForKey:@"demopage"];
self.imagesa = imagearray;
}
}

NSLog(@"Array Count %d",[self.imagesa count]);
NSLog(@"Another array Count %d",[self.imageArray count]);
}

这里 self.imagearray 是我的主数组,包含我所有的 JSON 数据,但我想从旧数据中解析新数据并将其添加到此处的 self.imagesa 数组中对于自图像,键的值是演示页面和 self .imagearray 计数是三 (3) 所以我希望我所有的三个索引值都进入 self.imagesa 但它只包含最后一个索引值请给我解决方案。我的 Web 服务链接在这里。 link

最佳答案

您的代码应如下所示。

id json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[json objectForKey:@"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[json objectForKey:@"data"];
[imageArray addObjectsFromArray:arr];
}

//do not alloc init if you have already alloc init array.
NSMutableArray *imagesa=[[NSMutableArray alloc]init];
for(NSDictionary *dict in imageArray )
{
[imagesa addObject:@{@"demopage":[dict valueForKey:@"demopage"]}];
}

NSLog(@"Array Count %lu",(unsigned long)[imagesa count]);
NSLog(@"Another array Count %lu",(unsigned long)[imageArray count]);

我的输出低于

Array Count 3

Another array Count 3

注意

如果您想将所有demopage 字典添加到imagesa 数组然后替换您的for 循环

for(NSDictionary *dict in imageArray )
{
NSArray *arr = (NSArray *)[dict valueForKey:@"demopage"];
[imagesa addObjectsFromArray:arr];
}

输出是

Array Count 69

Another array Count 3

关于ios - 如何在 iOS 中按索引将数组添加到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26906493/

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