Getting UITableView to populate with data from another class

风流意气都作罢 提交于 2019-12-04 20:57:33
- (void)viewDidLoad
{
    [super viewDidLoad];
    _modelDroplets = [[Droplets alloc]init];
    self.tableData = [_modelDroplets dropletsArray];
    [_modelDroplets getDropletsList];

    [self.tableView reloadData]; // reload the droplets table controller

}

In this method you are fetching droplets from a webservice. It is asynchronous, by the time tableView reloads the data it might not have completed fetching the data. You need to have a callback which will reload the tableView on completion of webservice.

EDIT :

Create a class method in Droplets to fetch all data

//Droplets.h
typedef void (^NSArrayBlock)(NSArray * array);
typedef void (^NSErrorBlock)(NSError * error);

//Droplets.m
+ (void)getDropletsWithCompletion:(NSArrayBlock)arrayBlock onError:(NSErrorBlock)errorBlock
{
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:kDigialOceanApiURL];
    [urlRequest setHTTPMethod:@"GET"];
    [urlRequest setCachePolicy:NSURLCacheStorageNotAllowed];
    [urlRequest setTimeoutInterval:30.0f];
    [urlRequest addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    [NSURLConnection sendAsynchronousRequest:urlRequest
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *responseData, NSError *error) {

                               if (error) {
                                   errorBlock(error);
                               }else{
                                   NSError *serializationError = nil;
                                   NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData
                                                                                        options:NSJSONReadingAllowFragments
                                                                                          error:&serializationError];

                                   arrayBlock(json[@"droplets"]);
                               }

                           }];

}

//DropletsList.h

- (void)viewDidLoad
{
    [super viewDidLoad];

    [Droplets getDropletsWithCompletion:^(NSArray *array) {
          self.modelDroplets = droplets;
          [self.tableView reloadData];
     } onError:^(NSError *error) {

           UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
           [alert show];
    }];

}

Disclaimer : Tested and verified :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!