【问题标题】:ios - removing any file, but not all files from the Document Directoryios - 从文档目录中删除任何文件,但不是所有文件
【发布时间】:2012-12-18 16:57:44
【问题描述】:

我有这段代码,它允许我指定要从我的文档目录中删除的特定文件。

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [[paths objectAtIndex:0] stringByAppendingString:@"/Podcasts"];

    NSString* checkIfFileExists = [documentsDirectoryPath stringByAppendingPathComponent:_fileName];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:checkIfFileExists error:NULL];

如果您想使用按钮删除文件,我可以看到这很有用,但不想只删除特定文件,如何引用 removeItemAtPath: 来处理数组中的任何文件?我不希望它一次删除所有文件。

【问题讨论】:

  • 对名为checkIfFileExists的变量使用-fileExistsAtPath:的值可能更有用
  • NSLog checkIfFileExists 并确保它有正确的路径。
  • 是的,同意,还在设置中,看看是否可以工作,我稍后会清理它:-)

标签: objective-c ios nsfilemanager nsdocumentdirectory


【解决方案1】:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [[paths objectAtIndex:0] stringByAppendingString:@"/Podcasts"];
NSString* checkIfFileExists = [documentsDirectoryPath stringByAppendingPathComponent:_fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isMyFileThere = [[NSFileManager defaultManager] fileExistsAtPath:checkIfFileExists];
if(isMyFileThere){

          [fileManager removeItemAtPath:checkIfFileExists error:NULL];
}
else{
          //file dont exists
}

【讨论】:

  • @JeffKranenburg 欢迎您
【解决方案2】:

您可以使用- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)errorNSFileManager 获取目录的内容。

https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html

然后遍历数组,将文件一个一个删除。

【讨论】:

    【解决方案3】:

    您可以使用相同的代码。

    但需要像这样添加文件名:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [[paths objectAtIndex:0] stringByAppendingString:@"/Podcasts"];
    NSString *file = [documentsDirectoryPath stringByAppendingString:@"%@",[yourFileNamesArray objectAtIndex:0];
    
    NSString* checkIfFileExists = [file stringByAppendingPathComponent:_fileName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:checkIfFileExists error:NULL];
    

    【讨论】:

    • yourFileNamesArray 与 NSArray *paths 不一样??
    • @JeffKranenburg: 不,它不是同一个数组,如果你已经有一个文件名如下的数组:file1.txt、file2.txt 等
    • 我相信他认为您要删除多个文件,因此将它们的名称存储在一个数组中。您可以将其替换为包含正确文件名的字符串文字,它会正常工作。
    • 好的,但是如果我有一个字符串文字,除非我弄错了,那不是将文件名硬编码到上面的方法中吗?我想让用户能够删除他们存储在文档文件夹中的单个文件,但我不知道那个文件
    • 我在此视图中拥有的唯一数组是用户文档文件夹中列出的内容。
    猜你喜欢
    • 2012-03-05
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 2013-02-07
    • 2011-08-14
    • 2013-01-28
    • 1970-01-01
    相关资源
    最近更新 更多