tmutton
tmutton

Reputation: 1101

iPhone JSON - Iterate NSArray and get values

I've been trying to solve this myself (I was awake all last night banging my head against a wall) but hopefully someone here can help me.

I have used this tutorial to connect to my JSON datasource (http://www.mobileorchard.com/tutorial-json-over-http-on-the-iphone/) and it works fine but I would now like to get the values (by object key I think).

My json data is as follows: [{"Id":"1","Name":"Richard","NameOfFile":"1.jpg"},{"Id":"395","Name":"Alex","NameOfFile":"390.jpg"}]

And the code i'm using to connect to it is as follows.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
    [connection release];

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [responseData release];

    SBJSON *json = [[SBJSON new] autorelease];
    NSArray *myArray = [json objectWithString:responseString error:nil];
    [responseString release];   

    for (int i = 0; i < [myArray count]; i++)
    {
        for(int colIndex = 0; colIndex < 5; colIndex++) 
        {
            UIImage * myimage = [UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: @"http://www.goweruk.com/Images/Uploaded/220/873.jpg"]]];
            UIImageView *myimageview = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,50.0f, 50.0f)];
            [myimageview setImage:myimage];

            CGRect frameRect = myimageview.frame;
            frameRect.origin.x = (frameRect.size.width + 14) * colIndex;
            frameRect.origin.y = (frameRect.size.height + 14) * i;
            myimageview.frame = frameRect;

            [self.view addSubview:myimageview];
            [myimageview release];
        }
    }
}

So what i'd like to do is inside that loop, get an item value. Does anyone know how I would do that?

Upvotes: 1

Views: 7859

Answers (1)

Jacob Relkin
Jacob Relkin

Reputation: 163238

That NSArray is an array of NSDictionary objects, so you will first need to get the dictionary at the desired index using objectAtIndex:, then iterate through the dictionary using for..in:

for (int i = 0; i < [myArray count]; i++)
{
    NSDictionary *dict = [myArray objectAtIndex:i];
    for(NSString *key in dict) {
       //do something with key or [dict objectForKey:key];
    }
}

Upvotes: 8

Related Questions