Chris Loonam
Chris Loonam

Reputation: 5745

iOS NSMutableArray sticking

I'm trying to populate a UITableView from an array that contains files in a directory

//in my header
@property (strong, nonatomic) NSMutableArray *files;
//in my tableView:cellForRow:atIndexPath:
static NSString *cellid = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
    cell.textLabel.text = [_files objectAtIndex:indexPath.row];
}
return cell;

(_files is set equal to [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self downloadsDir]; prior to this method being called) This works, and shows the correct files. The problem is if I add a file to the directory, and then use tableView reloadData, a new file will be added, but the title will be a duplicate of another file. Example

table view before adding file

++++++++++++++++++++++++++
text.txt
++++++++++++++++++++++++++
testing.txt
++++++++++++++++++++++++++

table view after adding file othertest.txt

++++++++++++++++++++++++++
text.txt
++++++++++++++++++++++++++
testing.txt
++++++++++++++++++++++++++
testing.txt
++++++++++++++++++++++++++

it should be

++++++++++++++++++++++++++
text.txt
++++++++++++++++++++++++++
testing.txt
++++++++++++++++++++++++++
othertest.txt
++++++++++++++++++++++++++

if I restart the app, it will show the correct files. But for some reason it does this. Anyone know what might be wrong?

Upvotes: 0

Views: 65

Answers (1)

Caleb
Caleb

Reputation: 124997

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
    cell.textLabel.text = [_files objectAtIndex:indexPath.row];
}
return cell;

You're not setting the cell label text except for when you allocate a new cell. Try this instead:

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
}
cell.textLabel.text = [_files objectAtIndex:indexPath.row];
return cell;

Same code, but I've moved the line where you set the cell's text so that it gets executed when you reuse a cell as well as when you create a new one.

Upvotes: 3

Related Questions