【问题标题】:Retrieve by specific file name from document directory in iOS从 iOS 中的文档目录中按特定文件名检索
【发布时间】:2013-06-21 09:45:32
【问题描述】:

现在我正在使用以下代码在 iOS 中按特定名称从文档目录中检索文件。

NSMutableArray *arrayToSearch = [[NSMutableArray alloc] init];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSError * error;

    arrayToSearch = (NSMutableArray *)[[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@/Manual.txt",documentsDirectory] error:&error];

我确定我在文档目录中有 Manual.txt 文件。

但是它在 tableView 中没有显示任何内容。

我还重新加载了 tableView。

有什么问题吗?

【问题讨论】:

  • 是的,我确定,因为我可以从文档目录中获取所有文件列表。

标签: ios cocoa-touch nsmutablearray nsfilemanager


【解决方案1】:

方法是contentsOfDirectoryAtPath:。阅读方法的名称。阅读文档中的描述。您传递的路径必须引用目录,而不是文件。

您尝试做的事情在逻辑上没有意义。如果您知道特定文件,那么为什么要搜索它?为什么要创建数组?

如果要查看文件是否存在,使用NSFileManagerfileExistsAtPath:方法。

如果你只想要数组中的文件名,那么:

NSString *filename = [documentsDirectory stringByAppendingPathComponent:@"Manual.txt"];
[arrayToSearch addObject:filename]; // since the array was pre-allocated

请不要使用stringWithFormat 创建文件名。像我上面那样使用正确的NSString 路径方法。

【讨论】:

  • 是的,兄弟。我得到了它。但我正在使用 NSMutableArray。我可以和@[文件名]一起使用吗?兄弟?
  • 由于您之前实际分配了可变对象,因此您应该执行[arrayToSearch addObject:filename];。我会更新我的答案。
猜你喜欢
  • 1970-01-01
  • 2014-07-09
  • 1970-01-01
  • 2023-03-31
  • 2015-11-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 2013-09-20
相关资源
最近更新 更多