Evgeniy Kleban
Evgeniy Kleban

Reputation: 6940

Correctly set numberOfRowsInSection

I have an app that load data using AFNetworking, parsing income JSON data and populate table. I use different class to manage JSON and to populate UITableView.

I need to correctly set number of rows. Problem is, i guess its method load too early, before we get any data from web. I tried following:

-(NSInteger)numberOfElements{


return [self.dataDictArray count];

}

And then:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return [self.handler numberOfElements];
}

When handler is an instance type of class, that deal with JSON and declare -(NSInteger)numberOfElements.

How can i set correct number of elements in such situation? Apparently tableView load before we got web data, that's kind of confusing.

Upvotes: 0

Views: 141

Answers (1)

SandeepAggarwal
SandeepAggarwal

Reputation: 1293

One way to do this is:

In success block of AFNetworking get method fire a notification

  #define NOTIFICATION_NAME @"LoadNotification"  

[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_NAME object:self];

In viewDidLoad method of UITableViewController subclass set the class as observer of notification

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedLoadingNotification:) name:NOTIFICATION_NAME object:nil];

In 'receivedLoadingNotification' method set the delegate and datasourceDelegate

-(void)receivedLoadingNotification:(NSNotification *) notification
{
    if ([[notification name] isEqualToString:NOTIFICATION_NAME])
    {
        [self.tableView setDelegate:self];
        [self.tableView setDataSource:self];
    }
}

So, the controller will only call the dataSource and delegate methods when JSON data is successfully loaded from AFNetworking. Hope it helps.

Upvotes: 1

Related Questions