开发者社区 问答 正文

关于iOS NSMutableArray的问题

需要填充一个数组的UITableview,其中包含文件。

//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设置为等同[[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self downloadsDir];

代码运行之后可以正确显示文件,问题是在目录中添加其他文件时,使用tableView reloadData,添加新文件但是标题会复制原来的。

比如:

添加文件之前的tableView

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

添加了文件othertest.txt之后:

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

正确的格式应该是这样:

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

重启应用就可以正常显示,不知道为什么?

展开
收起
爵霸 2016-03-24 09:19:01 1840 分享 版权
1 条回答
写回答
取消 提交回答
  • if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
        cell.textLabel.text = [_files objectAtIndex:indexPath.row];
    }
    return cell;

    因为你只有分配新单元时才设置单元标签text,试试这样:

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

    同样的代码,不过我删除了设置单元文本那行,这样在你创建新的或者重新使用cell都能执行。

    2019-07-17 19:11:53
    赞同 展开评论
问答分类:
问答标签:
问答地址: