Just trying to understand my table isn’t being populated when my view controller appears here. I’m using AIHTTPRequest to communicated with a REST API. The call returns an array of associative arrays (which I’m assuming I’ll have to cast to an NSArray of NSDictionaries).
In the header of my TableViewController:
@interface MyTableViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource> {
NSArray *homepageItems;
}
@property (nonatomic, retain) NSArray * homepageItems;
In the implementation:
@synthesize homepageItems;
....
- (void)viewDidLoad {
NSURL *url = [NSURL URLWithString:URL_TO_MY_API];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
When the data is returned:
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
id response = [responseString objectFromJSONString];
homepageItems = (NSArray *)response;
}
And in the Table View method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *dataItem = [homepageItems objectAtIndex:indexPath.row];
// Configure the cell...
cell.textLabel.text = [dataItem objectForKey:@"message"];
return cell;
}
When the view loads nothing is in the table. I suspect this is happening because when the table view method is fired homepageItems hasn’t been populated by the asynchronous method. How can I achieve the data being loaded into the table view?
Thanks,
EDIT: In my requestFinished method, I’ve examined the homepageItems object by doing the following:
for(NSDictionary *dictionary in homepageMMDs) {
NSLog(@"%@", [dictionary objectForKey:@"message"]);
}
And the proper messages from my API service are being logged.
You are not retaining the downloaded data:
Instead of:
You need to do: (crucially using
selfin front ofhomepageItems)