我有一个 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;
因为 NSMutableArray
是 NSArray
的子类,因此无需更改方法的返回类型。
关于ios - 使用 for 循环设置数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10905502/