Yhper
Yhper

Reputation: 193

UITableView reloadData not working

I a UITableView called tableView. It's data array called namesArray.

I have a function that adds a name to the array that looks like this:

-(void)addName:(NSString*)name
{
    [self.namesArray addObject: name];
    [self.tableView reloadData];
}

Note: I'm calling addNames: as a selector from NSNotificationCenter.

After I call reloadData on tableView, the last cell (the one that was added) is not showing on tableView, numberOfRowsInSection return the actual number so there is a space for another cell but there is not an actual cell.

I was debugging cellForRowAtIndexPath and I was found out that when cellForRowAtIndexPath called for the new cell it's all looks fine, it's seems like it's returning the correct cell so I really don't know what the problem is.

The code for cellForRowAtIndexPath:

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

    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }

    cell.textLabel.text=[self.namesArray objectAtIndex:indexPath.row];

    return cell;
}

numberOfRows:

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

Note: if I try to print the last object of namesArray using NSLog it's looking fine (the last object is the new one that was created) so it's a problem with reloading the data of tableView

screenshot after adding a new name (all the names + one place for a cell but it's blank (nto just the title, you can't even select it)): screenshot

Can you please help me? Thanks you very much!

Upvotes: 1

Views: 1337

Answers (1)

Kishan Raiyani
Kishan Raiyani

Reputation: 56

Try this:

dispatch_async(dispatch_get_main_queue(), ^{
           [self.tableView reloadData];
        }); 

It will call reloadData method on the main thread.

Upvotes: 1

Related Questions