domshyra
domshyra

Reputation: 952

Use a for loop to set values in an array

I have a UITableViewController that uses an array with values for every entry in the rows. I want to set the values of that array by iterating over values read from a JSON file.

This is the new method I have created to read that data into an array and return it to my view controller. I don't know where to return the array, or how to really set it.

+(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;

I know that my animalObj function worked when the data was local strings(@"Cat") and my dictionaryWithContentsOfJSONString works because I have tested, but I haven't used this function to set data to an array, only to UILabels, so this is where I am confused, on how to set this data into an array. But still use the For loop.

Upvotes: 0

Views: 2083

Answers (1)

ckhan
ckhan

Reputation: 4791

You want to use an instance of NSMutableArray, which will let you incrementally add elements to the array as you iterate with the for-loop:

...
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;

Because NSMutableArray is a subclass of NSArray, there's no need change the return type of your method.

Upvotes: 1

Related Questions