【问题标题】:List Contents of Directory in a UITableView在 UITableView 中列出目录的内容
【发布时间】:2010-12-16 22:53:14
【问题描述】:

我试图在 TableView 中列出 Ringtones 目录的内容,但是,我只获取所有单元格中目录中的最后一个文件,而不是每个单元格中的文件。这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    Profile_ManagerAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        cell.hidesAccessoryWhenEditing = YES;
    }

    cell.accessoryType = UITableViewCellAccessoryNone;
    //cell.textLabel.text = @"No Ringtones";
    //cell.textLabel.text = @"Test";

    NSString *theFiles;
    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *fileList = [manager directoryContentsAtPath:@"/Test"];
    for (NSString *s in fileList){
        theFiles = s;
    }
    cell.textLabel.text = theFiles;

    return cell;
}

它加载正常,没有错误,当我使用NSLog 时,它列出了目录中的所有文件就好了。我什至尝试过[s objectAtIndex:indexPath.row],但我得到 objectAtIndex: 错误。有人有什么想法吗?

【问题讨论】:

  • 也许您应该在标题中创建数组,以便您可以在主文件中的任何位置访问该文件。如果您不这样做,那么您如何设置表格项目的数量,除非您已经预先设置了数量,但是如果您让人们添加或删除文件,那么获取目录中的项目数量会更容易。跨度>

标签: ios uitableview nsarray nsfilemanager


【解决方案1】:

我真的很喜欢在这里提问,因为不到 10 分钟,我就回答了我自己的问题!

这就是我让上面的代码工作的方式:

NSMutableArray *theFiles;
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager directoryContentsAtPath:@"/Test"];
for (NSString *s in fileList){
    theFiles = fileList;
}
cell.textLabel.text = [theFiles objectAtIndex:indexPath.row];
return cell;

我刚刚将 NSString 设为 NSMutableArray,这样我就可以使用 objectAtIndex。现在修剪文件扩展名!

【讨论】:

  • 你确实意识到你在这里复制了几次数组,这是非常低效的。您不需要 for 循环,我怀疑您根本不需要创建数组的可变副本。
【解决方案2】:

你应该删除 NSString、NSMutableArray 和 for 循环.. 最终代码应该是这样的:

NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager directoryContentsAtPath:@"/Test"];
cell.textLabel.text = [fileList objectAtIndex:indexPath.row];
return cell;

顺便说一句,这个文件列表和管理器为每个单元格重复创建..所以最好将它设置为 UITableViewController 的全局变量并只分配 1

【讨论】:

    【解决方案3】:

    您的 for 循环只是遍历文件并将 theFiles 设置为当前路径。所以在循环结束时,theFiles 将只是集合中的最后一个字符串。

    尝试类似:

    cell.textLabel.text = [fileList objectAtIndex:indexPath.row];
    

    【讨论】:

    • 你在这个答案上是半正确的,实际上不正确的是允许 objectAtIndex 的 NSMutableArray。
    • objectAtIndex 是在 NSArray 上提供的,不是吗?
    猜你喜欢
    • 2019-02-27
    • 2013-12-07
    • 2011-06-10
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    相关资源
    最近更新 更多