Hi I am pretty new to creating Table View Controllers. I'm having difficulty trying to load data retrieved via Json in the ViewDidLoad section, into a table view controller. The first thing I noticed is that the array where I eventually put my json data (dataArray) is not available in: numberOfRowsInSection, so I declared it outside viewDidLoad but now see that when I debug the array is empty when it gets to numberOfRowsInSection. I did test the retrieval code beforehand so am sure it works. I have a couple of questions: 1. why is that dataArray is empty in the other methods? 2. is it fine to load data for displaying in tableviews in ViewDidLoad or should I really be loading this data somewhere else where it is more visible and available for use by the tableview methods?
Here is the code:
NSArray *dataArray = nil;
- (void)viewDidLoad {
[super viewDidLoad];
dataArray = [[NSArray alloc] init];
// Set URL variable with Token
NSString *token = @"99fdf505547d607e65b8b8ff16113337";
NSString *teacherUrl = [NSString stringWithFormat: @"https://covle.com/apps/api/nextdoorteacher/teachers?t=%@",token];
// Set up the session configuration
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
[[session dataTaskWithURL:[NSURL URLWithString:teacherUrl]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSLog(@"response ==> %@", response);
if (!error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200){
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&error];
NSLog(@" heres the serialised json ===> %@", jsonData);
// move serialised JSON into Array (as the data contained is in array)
dataArray=(NSArray*)[jsonData copy];
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return dataArray.count;
NSLog(@"Array count is set to ===> %@", dataArray.count);
Any help to understand and fix this would be very much appreciated. Thanks
For this
NSArray *dataArray=(NSArray*)[jsonData copy];
You are creating a new local variable named dataArray which is NOT the same as the global dataArray which u allocated in viewDidLoad, so just write this
dataArray = (NSArray*)[jsonData copy];
and you will get the array count as expected in numberOfRowsInSection
EDIT:
call [self.tableview reloadData]
after dataArray = (NSArray*)[jsonData copy]
for calling tableview delegate methods to fire once again!