Saurabh Dutta Saurabh Dutta - 5 months ago 8
iOS Question

Iterate from multi-dimension array in iOS

How to iterate from this multi-dimensional array in iOS ?
This data is coming from JSON

(
(
"burger meal",
"getImage.ashx?id=1",
150,
300,
"get a free burger"
),
(
"chinese combo",
"getImage.ashx?id=2",
350,
700,
"get a combo free"
),
(
"cheeese cake",
"getImage.ashx?id=3",
350,
700,
"get a cake free with meal"
)
)


I need to use object at index 3 e.g. = 150,350,350 in UITableView .

I have tried this

NSArray *array = jsonArray;

for (NSArray *newArray in array) {
[newArray addObjectFromArray:array];
}

Answer

This is simple. Let TableView iterate the arrays for you. Your tableView is already iterating, don't add to overhead by iterating over the array yourself. You will just waste processing power if you do.

First, modify your numberOfRowsInSection delegate method like this:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  [jsonArray count]; //Provide your json array here.
}

Then you have to do this in your cellForRowAtIndexPath method:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Do everything that you need to do to get the cell. Here we will deal with only string retrieval from json array.
    if(jsonArray count]>indexPath.row){
        NSArray *innerArray = [jsonArray objectAtIndex:indexPath.row]; //You got the inner array
        if(innerArray count]>2){
             NSString *yourDesiredString = [innerArray objectAtIndex:2]; //You got the string. Use it now as you wish. It will be 150 for the first cell, 350 for the second and 350 for the third one as well.
         }

    }

}

I have not added any exception checks here, that's what you have to do yourself. I have added basic checks to prevent crashes in case of irrelevant data, you should expand on that.

This is with the assumption that you wish to set this string to each cell. If I have misunderstood your question or you need to ask something, leave a comment

Comments