【发布时间】:2015-05-27 19:54:21
【问题描述】:
我知道这是 Stack Overflow 上的一个常见问题,但不幸的是,没有人能够引导我找到我的解决方案。
我正在尝试在UITableView 中列出我的文档目录中的文件。 (我还有另一个 tableview 显示我连接到的设备)
我知道我收到了这个错误,因为它说我的数组有 0 个对象,而我正在尝试访问索引 1 处的对象。
但我的文档目录中有一个文件。
如果我有 2 个文件,当我删除 1 个时,我会收到此错误。当应用程序重新启动时,它会正确显示 UITableView 并删除文件。
我从这里得到了我的代码: Objective-C: How to list files from documents directory into a UITableView?
这是我的内容:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (tableView == _tblConnectedDevices){
return [_arrConnectedDevices count];
}
if ([filePathsArray count] > 0){
return [filePathsArray count];
}
else
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if (tableView == _tblConnectedDevices){
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellIdentifier"];
}
cell.textLabel.text = [_arrConnectedDevices objectAtIndex:indexPath.row];
return cell;
} else {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSString *last = [documentsDirectory stringByAppendingPathComponent:[filePathsArray objectAtIndex:indexPath.row]];
NSString *last2 = [[last lastPathComponent] stringByDeletingPathExtension];
cell.textLabel.text = last2;
return cell;
}
}
我的删除无效:
-(IBAction)deleteFile:(id)sender{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt", fileName]];
NSError *error;
[[NSFileManager defaultManager] removeItemAtPath:fullPath error:&error];
[_cellView reloadData];
}
【问题讨论】:
-
这段代码中有一些非常奇怪的逻辑。 filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];在 cellForRow 中。并返回 [filePathsArray 计数];在您的行数中。你确定你明白你想要得到什么?
-
在 deleteFile 中重新加载您的 filePathArray:同时设置断点并查看数组中有多少文件。
-
我是相当新的@PavelGatilov,我使用的是我在网上找到的代码,它可以很好地显示我想查看的文件,我唯一苦苦挣扎的是删除后文档目录中的某些内容,表格视图在删除文件后正确重新加载。
-
所以代码没有工作得很好。
-
@PavelGatilov 感谢您的回答,如果您将其发布为正确答案,它会起作用。我在 cellforRow 中添加了一个 if 检查我的数组是否为空,还检查文件夹是否为空。
标签: ios objective-c xcode uitableview nsdocumentdirectory