gpt4 book ai didi

objective-c - NSFileManager 文件存在于路径 :isDirectory issue

转载 作者:行者123 更新时间:2023-12-04 03:06:45 26 4
gpt4 key购买 nike

有人可以帮助我了解我在使用此方法时做错了什么吗?

我试图递归地检测目录的内容并在每个目录中创建一个 xml 文件。非递归完美运行并输出正确的 xml 文件。递归阻塞目录检测并在“目录”元素下添加所有文件 + 目录。

_dirArray = [[NSMutableArray alloc] init];
_fileArray = [[NSMutableArray alloc] init];

NSError *error;
NSFileManager *filemgr = [NSFileManager defaultManager];
NSArray *filelist = [filemgr contentsOfDirectoryAtPath:dirPath error:&error];

for (int i = 0; i < filelist.count; i++)
{
BOOL isDir;
NSString *file = [NSString stringWithFormat:@"%@", [filelist objectAtIndex:i]];
[_pathToDirectoryTextField stringValue], [filelist objectAtIndex:i]];

if ([filemgr fileExistsAtPath:dirPath isDirectory:&isDir] && isDir) // I think this is what is crapping out.
{
[_dirArray addObject:file];
}
else
{
if ([file hasPrefix:@"."])
{
// Ignore file.
}
else
{
[_fileArray addObject:file];
}
}
}

感谢大家的提示。

最佳答案

我可以看到“if ([fileManager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir)”来自 Apple 在文档中的示例,但是将它零碎地复制并与其他一起使用是一个非常糟糕的主意,除非你只想得到目录或删除的文件,因为它的意思是:

if (itexists and itsadirectory){
//its a existing directory
matches directories
}else{
//it is not a directory or it does not exist
matches files that were deleted since you got the listing
}

这是我的做法:

NSString *dirPath = @"/Volumes/Storage/";

NSError *error;
NSFileManager *filemgr = [NSFileManager defaultManager];
NSArray *filelist = [filemgr contentsOfDirectoryAtPath:dirPath error:&error];

for (NSString *lastPathComponent in filelist) {
if ([lastPathComponent hasPrefix:@"."]) continue; // Ignore file.
NSString *fullPath = [dirPath stringByAppendingPathComponent:lastPathComponent];
BOOL isDir;
BOOL exists = [filemgr fileExistsAtPath:fullPath isDirectory:&isDir];

if (exists) {
if (isDir) {
[_dirArray addObject:lastPathComponent];
}else{
[_fileArray addObject:lastPathComponent];
}
}
}

关于objective-c - NSFileManager 文件存在于路径 :isDirectory issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9489153/

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