【问题标题】:Remove all files from memory using NSFileManager使用 NSFileManager 从内存中删除所有文件
【发布时间】:2013-03-12 06:29:10
【问题描述】:

如何删除使用 NSFileManager 保存的所有文件?我找到了类似于下面代码的内容,但您需要提供 filePath,并且由于我需要删除我保存的所有图像,所以我不知道所有图像路径/名称?

[[NSFileManager defaultManager] removeItemAtPath:filePath error:NULL];

【问题讨论】:

标签: ios objective-c


【解决方案1】:

首先从该特定文件夹中获取所有项目:

NSString  *filePath = [NSString stringWithFormat:@"your folder path where you have saved those images"];
NSArray *files = [fileManager contentsOfDirectoryAtPath:filePath 
                                                  error:nil];

这将是刚刚遍历数组的文件数组。并使用:

  for(NSString *filename in files)
   {
    NSString  *filePath = [NSString stringWithFormat:@"filepath/%@",filename];
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:NULL];
   }

这应该可以解决问题。

【讨论】:

  • 我试过这个但是 [[NSFileManager defaultManager] removeItemAtPath:filePath error:NULL];返回 NO 表示有错误
  • 这是错误:操作无法完成。 (可可错误 4。)
  • NSFileNoSuchFileError = 4, // 尝试对不存在的文件进行文件系统操作
  • @Shinonuma:在获取文件数组时,您必须提供文件夹的路径。如果要从临时文件夹中删除文件,请提供临时文件夹的路径。有关更多信息,请查看 SO 问题:stackoverflow.com/questions/14378768/…
【解决方案2】:

您必须将图像保存到任何文件夹,例如 Documents Directory、Library、Caches 或 Temp 文件夹。您需要使用以下代码获取保存图像的任何目录中的所有图像..

-(NSArray*)getImagesFromDirectory:(NSString*)imageDirectoryPath{

   NSFileManager *fileManager = [[NSFileManager alloc] init];
   NSArray *files = [fileManager contentsOfDirectoryAtPath:imageDirectoryPath 
                                          error:nil];
   return files;
}

然后循环删除路径中的图像

 NSArray *images=[self getImagesFromDirectory:@"DIRECTORYPATH"];
 NSFileManager * fileManager = [[NSFileManager alloc] init];
 for(NSString *imagePath in images){
     [fileManager removeItemAtPath:imagePath];
 }

【讨论】:

    猜你喜欢
    • 2012-05-23
    • 1970-01-01
    • 2014-12-22
    • 2015-09-18
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    相关资源
    最近更新 更多