Nono Nono - 4 months ago 19
iOS Question

Objective-C: TableView in UIViewController - Data just load after a click

I have a table view in a UIViewController and I load the data from a database. But when I start the app the table is empty. Only when I click on the table the data will appear. Can someone tell me what I must change? Here is my code:

#import "DashboardViewController.h"
#import <UIKit/UIKit.h>

@interface DashboardViewController ()

@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *data;

@end

@implementation DashboardViewController


- (void)viewDidLoad {
[super viewDidLoad];

}

- (NSMutableArray *)data {

if(!_data){

_data = [[NSMutableArray alloc] init];

NSString *username = [[NSUserDefaults standardUserDefaults] stringForKey:@"username"];

NSURLSession *session = [NSURLSession sharedSession];
NSString *url = [NSString stringWithFormat:@"http://www.example.net/getData.php?user=%@", username];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSString *errorCode = [json valueForKey:@"error"];

if([errorCode isEqualToString:@"e0"]){

NSArray *myData = [json objectForKey:@"myData"];

for (int i = 0; i < [myData count]; i++) {
[_data addObject:[myData objectAtIndex:i]];
[self.tableView reloadData];
}

}

}];

[dataTask resume];

}

return _data;

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.data count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

cell.textLabel.text = [[self.data objectAtIndex:indexPath.row] objectForKey:@"name"];

return cell;
}

@end

Answer

not like

for (int i = 0; i < [myData count]; i++) {
                [_data addObject:[myData objectAtIndex:i]];
                [self.tableView reloadData];
            }

do like

 for (int i = 0; i < [myData count]; i++) {
                [_data addObject:[myData objectAtIndex:i]];

            }

          if (_data.count>0)
         {
         dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
          [self.tableView reloadData];
      });
        }