gpt4 book ai didi

objective-c - 如何删除obj c中文件夹的内容

转载 作者:行者123 更新时间:2023-11-28 20:35:07 38 4
gpt4 key购买 nike

我用下面的方法删除了文件夹中的所有内容

NSFileManager *fm = [NSFileManager defaultManager];
NSArray* arrFilePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * strFilePath = [arrFilePath objectAtIndex:0];
NSString *directory = [strFilePath stringByAppendingPathComponent:@"Electronic_Instrumentation-Sapna_publications"];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error])
{
directory = [directory stringByAppendingPathComponent:file];
BOOL success = [fm removeItemAtPath:directory error:&error];
file = nil;
if (!success || error)
{
NSLog(@"Failed to remove files");
}
}

但它只删除目录中的第一个文件

假设我在 dorectory 中有 3 个文件 file1.txt、file2.txt、file3.txt

当我调用此方法时,它只会删除 file1.txt 而不会删除其他文件,如果我再次调用该方法,它会删除 file2.txt 但不会删除 file3.txt

我该如何解决这个问题??

有什么办法可以删除目录吗??提前谢谢

最佳答案

问题是您在第一次执行循环时更改了目录。此后,您使用的是无效路径。第一次通过循环,directory 有类似的东西:

/path/to/the/file1.txt

下一次循环时,您附加下一个文件名,因此 directory 变为:

/path/to/the/file1.txt/file2.txt

这显然行不通。

找到这样的问题的最佳方法是在调试器中单步调试代码,边走边观察相关变量。

修复这个问题的正确方法是停止修改目录,现在您知道它是什么了。您可以使用临时变量,如下所示:

for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) 
{
NSString *path = [directory stringByAppendingPathComponent:file];
BOOL success = [fm removeItemAtPath:path error:&error];

或者您可以只使用 -stringByAppendingPathComponent: 的结果作为 -removeItemAtPath:error: 的参数,如下所示:

for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) 
{
BOOL success = [fm removeItemAtPath:[directory stringByAppendingPathComponent:file]
error:&error];

is there any way to delete a directory ??

您可以查看文档中的 -removeItemAtPath:error:。我会为你节省一次旅行:

A path string indicating the file or directory to remove. If the path specifies a directory, the contents of that directory are recursively removed.

是的,有一种删除目录的简单方法。只需在 -removeItemAtPath:error:path 参数中指定目录即可。

关于objective-c - 如何删除obj c中文件夹的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10844988/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com