Search code examples
iosuitableviewcellreloaddata

UITableView reloadData not work


this is my UITableView code

in viewDidLoad

self.audioHistoryTableView = [[UITableView alloc] init];
self.audioHistoryTableView.delegate = self;
self.audioHistoryTableView.dataSource = self;

table view

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"numberOfRowsInSection");
    NSLog(@"tableeeeeeee %lu",(unsigned long)[audioHistory count]);
    return [audioHistory count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSLog(@"cellForRowAtIndexPath");
    NSString *CellIdentifier = @"historyCell";
    UITableViewCell *cell = (UITableViewCell *)[self.audioHistoryTableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Configure the cell...
    NSString *audio = [audioHistory objectAtIndex:indexPath.row];
    cell.textLabel.text = audio;

    return cell;
}

when I add data and call reload

NSArray *newItem = [NSArray arrayWithObject:@"new audio!"];
NSLog(@"new item : %@",newItem);

[audioHistory addObjectsFromArray:newItem];
[self.audioHistoryTableView reloadData];

I know it's not work because I add new data and change to other page, when back to this page the added data was shown.


Solution

  • Can you set the delegate and datasource via the interface builder instead? Also if it's made in the interface builder why do you have to initialise the table? Remove this:

    self.audioHistoryTableView = [[UITableView alloc] init];
    self.audioHistoryTableView.delegate = self;
    self.audioHistoryTableView.dataSource = self;
    

    then in the interface builder control drag from the UITableView up to the UIViewController and set the delegate to self. And do that again and set the data source to self. Try that