【问题标题】:iOS NSMutableArray stickingiOS NSMutableArray 坚持
【发布时间】:2013-04-09 03:05:44
【问题描述】:

我正在尝试从包含目录中文件的数组中填充 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,则会添加一个新文件,但标题将与另一个文件重复。示例

添加文件前的表格视图

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

添加文件后的表格视图othertest.txt

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

应该是

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

如果我重新启动应用程序,它将显示正确的文件。但出于某种原因,它会这样做。有谁知道可能出了什么问题?

【问题讨论】:

    标签: iphone ios objective-c uitableview nsmutablearray


    【解决方案1】:
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
        cell.textLabel.text = [_files objectAtIndex:indexPath.row];
    }
    return cell;
    

    除了分配新单元格时,您不会设置单元格标签文本。试试这个:

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

    相同的代码,但我已经移动了您设置单元格文本的行,以便在您重用单元格以及创建新单元格时执行它。

    【讨论】:

    • 谢谢,这行得通。当他们允许我时,我会将其标记为正确。
    • 很常见的问题。很高兴能提供帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多