有人可以帮我理解我用这种方法做错了吗?
我正在尝试以递归方式检测目录的内容,并在每个目录中创建一个xml文件。非递归完美地工作并输出正确的xml文件。在dir检测上递归扼流并在“目录”元素下添加所有文件+目录。
_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];
}
}
}
感谢任何提示人员。
答案 0 :(得分:4)
我可以看到“if([fileManager fileExistsAtPath:fontPath isDirectory:&amp; isDir]&amp;&amp;&amp; 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];
}
}
}