Search code examples
iosobjective-cjsonnsarrayafnetworking

Add JSON Responses to Array


The endpoint JSON response is always just one array, with two dictionary items.

[
    {
        "item_1": "Austin",
        "item_2": "Texas"
    }
]

I need to make an item_1 and item_2 array, that are able to add items to them every time a new call is made to the endpoint. Have any ideas of the best way to set this up?

Right now, I'm adding a property:

@property (strong, nonatomic) NSMutableArray *item1Array;

Then setting that item1Array property equal to the response from the JSON endpoint:

self.item1Array = response;
NSLog(@"Response Array: %@", self.item1Array);

Logging it:

2016-04-01 13:35:42.787 A[66185:7391524] Response Array: (
        {
        "item_1" = Austin;
        "item_2" = Texas;
    }
)

But getting stuck when trying to add the new responses to the item1Array and item2Array.

Ultimately, I'd like the item1Array to have multiple items in it that reflect the items that were retrieved with the query to the endpoint (i.e. [@"Austin", @"Denver"]).

Any help or different ways of thinking about this than what I'm doing would be much appreciated.


Solution

  • Create your two NSMutable arrays. According to your json we have only 1 object for array and in that object there is a dictionary with 2 keys and values.

    Firstly initialize your Mutable arrays somewhere in viewDidLoad

    item1Array = [[NSMutableArray alloc] init];
    item2Array = [[NSMutableArray alloc] init];
    

    Then append whenever you get response.

    //Appending item_1 in item1Array which is a NSMutableArray
    [item1Array addObject:[[responseArray objectAtIndex:0] valueForKey:@"item_1"]];
    
    //Appending item_2 in item2Array which is a NSMutableArray
    [item2Array addObject:[[responseArray objectAtIndex:0] valueForKey:@"item_2"]];