【问题标题】:Deleting all the files in the iPhone sandbox (documents folder)?删除 iPhone 沙箱(文档文件夹)中的所有文件?
【发布时间】:2011-06-15 03:55:26
【问题描述】:

有没有一种简单的方法可以删除我保存在应用程序文档文件夹中的所有文件(图像)?

【问题讨论】:

标签: iphone ios ios4


【解决方案1】:
NSFileManager *fileMgr = [[[NSFileManager alloc] init] autorelease];
NSError *error = nil;
NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
if (error == nil) {
    for (NSString *path in directoryContents) {
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
        BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
        if (!removeSuccess) {
            // Error handling
            ...
        }
    }
} else {
    // Error handling
    ...
}

【讨论】:

  • 它在大多数情况下都有效。但事实证明 removeItemAtPath 需要完整的文件路径。所以我使用了这个 NSString *myFilePath = [documentsDir stringByAppendingPathComponent:path];谢谢。
  • 没错,吉娜。我的错误。我要更正上面的代码。
  • 如果可行,最好删除Untested code: 评论。谢谢
  • 每次执行此操作时都会收到 EXC_BAD_ACCESS。但它会删除我沙盒的内容。如何防止错误?有什么想法吗?
  • 我将文档目录作为未声明的标识符。使用 NSDocumentDirectory 也不起作用。它说,不兼容的整数到指针的转换。
【解决方案2】:
- (void)removeFile
{
    // you need to write a function to get to that directory
    NSString *filePath = [self getDirectory];
    NSFileManager *fileManager = [NSFileManager defaultManager];  
    if ([fileManager fileExistsAtPath:filePath]) 
    {
        NSError *error;
        if (![fileManager removeItemAtPath:filePath error:&error])
        {
            NSLog(@"Error removing file: %@", error); 
        };
    }
}

我相信这更短。

【讨论】:

  • 看来这只删除了一个文件或目录
【解决方案3】:

代码不适用于 IOS 7 和 Xcode 5,因此经过编辑后可用于我的应用程序。 非常感谢@Ole Begemann 和@pablasso。

-(void)EmptySandbox
{
    NSFileManager *fileMgr = [[NSFileManager alloc] init];
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSArray *files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];

    while (files.count > 0) {
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
        if (error == nil) {
            for (NSString *path in directoryContents) {
                NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
                BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
                files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];
                if (!removeSuccess) {
                    // Error
                }
            }
        } else {
            // Error
        }
    }
}

【讨论】:

  • 如果您使用 CoreData,请注意这也会删除您的模型
  • 谢谢,这段代码就像一个魅力。我是一个新手,我碰巧在 iPad 上用 NSMutableDictionary 覆盖了存储的存档 NSMutableArray。拯救我的生命
【解决方案4】:
 NSFileManager *fileMgr = [[[NSFileManager alloc] init] autorelease];
NSError *error = nil;
NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
 if (error == nil) {
   for (NSString *path in directoryContents) {
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
    BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
    if (!removeSuccess) {
        // Error handling
        ...
    }
}
} else {
 // Error handling
...
}

【讨论】:

    【解决方案5】:

    它可能不适用于所有情况,但通常将所有文件放在 Documents Directory 内的自定义目录中,然后使用 removeItemAtPath:error: 删除该目录并重新创建它会更有效。例如:

    // Clear cache
    NSError *error;
    [[NSFileManager defaultManager] removeItemAtPath:cacheDirectory error:&error];
    if (error)
    {
        // error handling
    }
    
    // Create cache directory again
    NSError *error2;
    [[NSFileManager defaultManager] createDirectoryAtPath:cacheDirectory withIntermediateDirectories:YES attributes:nil error:&error2];
    if (error2)
    {
        // error handling
    }
    

    【讨论】:

      【解决方案6】:

      对于 Swift 开发者:

      let fileMgr = NSFileManager()
      let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
      if let directoryContents = try? fileMgr.contentsOfDirectoryAtPath(dirPath)
      {
          for path in directoryContents 
          {   
              let fullPath = (dirPath as NSString).stringByAppendingPathComponent(path)
              do 
              {
                  try fileMgr.removeItem(atPath: fullPath)
                  print("Files deleted")
              } 
              catch let error as NSError 
              {
                  print("Error deleting: \(error.localizedDescription)")
              }
          }
      }
      

      【讨论】:

        【解决方案7】:

        带有一些额外功能的 Swift 2.1:

        do {
            let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
            let documentsDirectory = paths[0]
            let documentsDirectoryURL = NSURL(fileURLWithPath: paths[0])
        
            let directoryContents = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(documentsDirectory)
        
            var totalMegaBytes: Double = 0
            var nrOfFiles = 0
        
            for filename in directoryContents {
                let file = documentsDirectoryURL.URLByAppendingPathComponent(filename)
        
        
                let fileAttributes = try NSFileManager.defaultManager().attributesOfItemAtPath(file.path!)
                let fileSize = fileAttributes[NSFileSize] as! Double            
                totalMegaBytes += fileSize/1024/1024
        
                do {
                    try NSFileManager.defaultManager().removeItemAtURL(file)
                    nrOfFiles++
                }catch let error as NSError{
                    print("> Emptying sandbox: could not delete file", filename, error)
                }
            }
        
            print("> Emptying sandbox: Removed \(nrOfFiles) files with a total of \(round(totalMegaBytes))MB")
        
        }catch let error as NSError{
            print("> Emptying sandbox: Error emptying sandbox", error)
        }
        

        【讨论】:

        • 我得到“从这里抛出的错误没有被处理,因为封闭的 catch 不是详尽的”
        • 我支持你。但是你真的应该考虑删除这个:“let error as NSError”。或者可能对上述错误有其他解决方案
        • 我没有收到那个警告。 NSError 不是尽可能详尽吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多