简体   繁体   中英

Table View and AFNetworking Asynchronous Call

I'm new to iOS development and I am trying to figure out what the best solution to my problem would be. I have a UITableViewController class which calls a method named fetchModules in the viewDidLoad . This fetches all the data I need for my table using AFNetworking 2.

However, my table delegate methods such as numberOfRowsInSection and cellForRowAtIndexPath are failing because the AFNetworking call has not finished yet and the array I am using to store the data has not been populated.

The actual error I am getting is

Terminating app due to uncaught exception 'NSRangeException'

Here's my code:

#import "HistoryTableViewController.h"

@interface HistoryTableViewController ()

@property NSArray *modules;

@end

@implementation HistoryTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.modules = [[NSArray alloc] init];

    [self fetchModules];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)fetchModules
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    [manager.requestSerializer setValue:self.token forHTTPHeaderField:@"X-Auth-Token"];

    [manager GET:@"http://myurl.com/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        //NSLog(@"JSON: %@", responseObject);
        self.modules = [responseObject objectForKey:@"data"];
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}

#pragma mark - Table view data source

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.modules && self.modules.count) {
        return self.modules.count;
    } else {
        return 0;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"Cell Identifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
    }

    NSDictionary *module = [self.modules objectAtIndex:indexPath.row];
    cell.textLabel.text = [module objectForKey:@"code"];

    return cell;
}

Suggestions?

It's pretty much common solution for async network call.

Add [self.tableView reloadData] inside the AFNetworking success block :

- (void)fetchModules
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    [manager.requestSerializer setValue:self.token forHTTPHeaderField:@"X-Auth-Token"];

    [manager GET:@"http://myurl.com/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        //NSLog(@"JSON: %@", responseObject);
        self.modules = [responseObject objectForKey:@"data"];

       [self.tableView reloadData];

    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}`enter code here`

I think the conditions should be as below.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.modules != nil && self.modules.count > 0) {
        return self.modules.count;
    } else {
        return 0;
    }
}

Also do not forget to reload table after you get the response.

Few corrections may help you. First synthesize property "modules". Also in delegate method for creating Table Cell ensure that if "modules" is empty then that method should do no operation on "modules" property and just return "cell". I hope this helps you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM