OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在iOS中按索引将数组添加到数组索引中? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 03:19
标题: ios - 如何在iOS中按索引将数组添加到数组索引中?

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

我的代码就像

-(void)fetchedDataNSData *)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-images 键的值是演示页面和 Self .imagearray 计数是三个(3)所以我希望我所有的三个索引值都包含在 self.imagesa 中,但它只包含最后一个索引值,请给我解决方案。我的 Web 服务链接在这里。 link



Best Answer-推荐答案


您的代码应如下所示。

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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4