Search code examples
iosjsonnsmutablearraytableviewcell

tableView not populating with data from array


I'm new to iOS development and Objective-C programming so forgive my "noobiness".

Here's the thing, I have a function that builds an array getting data from a JSON object. I then have a second function, responsible for filling a tableView with data from contained in my array.

Problem is, the content of this array does not seem accessible from my tableView function, even though the array has been added to my header file and implemented in the main file. The tableView remains empty...

Do you have any idea why that is?

Here are the functions, thanks a ton for your help!

1) Array building function:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];

    //Get data
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];

    //Extract titles
    NSMutableArray *myResults = [[NSMutableArray alloc] init];
    NSArray *results = [res objectForKey:@"data"];

    for (NSDictionary *result in results) {
        NSString *title = [result objectForKey:@"colors"];
        NSLog(@"colors: %@", colors);
        [myResults addObject:colors];
    }

    self.colorNames = myResults;    
}

2) TableView filling function:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

//Set cell text
NSString *colorString = [self.colorNames objectAtIndex: [indexPath row]];
NSLog(@"%@",colorString);
cell.textLabel.text = colorString;

    return cell;
}

Solution

  • are you sure you reload your table view data after receiving your json data? I would suggest a [self.tableView reloadData]; at the end of your connection:didReceiveData: method. Otherwise the method tableView:cellForRowAtIndexPath: will be called only once after you view was loaded.

    Cheers, anka