ios - 使用 for 循环设置数组中的值

标签 ios json for-loop

我有一个 UITableViewController,它使用一个数组,其中包含行中每个条目的值。 我想通过迭代从 JSON 文件读取的值来设置该数组的值。

这是我创建的新方法,用于将该数据读入数组并将其返回到我的 View Controller 。我不知道在哪里返回数组,也不知道如何真正设置它。

+(NSArray *)setDataToJson{
NSDictionary *infomation = [NSDictionary dictionaryWithContentsOfJSONString:@"Test.json"];
NSArray *test = [infomation valueForKey:@"Animals"];
for (int i = 0; i < test.count; i++) {
    NSDictionary *info = [test objectAtIndex:i];
    NSArray *array = [[NSArray alloc]initWithObjects:[Animal animalObj:[info valueForKey:@"AnimalName"] 
location:[info valueForKey:@"ScientificName"] description:[info valueForKey:@"FirstDesc"] image:[UIImage imageNamed:@"cat.png"]], nil];
        return array;

我知道当数据是本地字符串(@“Cat”)时我的animalObj函数可以工作,并且我的dictionaryWithContentsOfJSONString可以工作,因为我已经测试过,但我还没有使用此函数将数据设置为一个数组,仅适用于 UILabels,所以这就是我对如何将此数据设置到数组中感到困惑的地方。但仍然使用For循环。

最佳答案

您想要使用的实例 NSMutableArray , 这将使您可以在添加元素时逐渐向数组中添加元素 使用 for 循环进行迭代:

...
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < test.count; i++) { 
    NSDictionary *info = [test objectAtIndex:i]; 
    Animal *animal = [Animal animalObj:[info valueForKey:@"AnimalName"]  
                              location:[info valueForKey:@"ScientificName"] 
                           description:[info valueForKey:@"FirstDesc"] 
                                 image:[UIImage imageNamed:@"cat.png"]];
    [array addObject:animal];
}
return array;

因为 NSMutableArrayNSArray 的子类,因此无需更改方法的返回类型。

关于ios - 使用 for 循环设置数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10905502/

相关文章:

ios - 为 Xcode 安装 OpenSSL 库

objective-c - 从 uiimageview 获取旋转后的图像

java - 如何直接提供 JSON 输入作为字符串参数

json - 将包含几何的 JSON 转换为 postgreSQL

javascript - 如何将 javascript 数组或 JSON 存储到 php 中

iphone - MKAnnotation : Clicking on the text in MKAnnotation info view should call a number

java while 循环没有中断

c++ - 如何在 std::map 中使用基于范围的 for() 循环?

C:创建具有唯一数字的二维数组

ios - Swift:什么是 .swift-version 文件?