gpt4 book ai didi

objective-c - 使用 NSDirectoryEnumerator 为文件系统建模

转载 作者:行者123 更新时间:2023-12-03 17:27:37 25 4
gpt4 key购买 nike

我正在尝试从给定的起始路径对文件系统的结构进行建模。目标是从该路径开始创建文件系统的标准 NSOutlineView

我有一个名为 fileSystemItem 的模型对象。它具有以下(非常标准的)关系和属性:

  • parentItem(指向另一个fileSystemItem对象)
  • isLeaf(YES 对于文件;NO 对于文件夹)
  • childrenItems(其他 fileSystemItems 的数组)
  • fullPath(NSString;对象的文件路径)

我的问题是:如何使用 NSDirectoryEnumerator 构建模型?如果我这样做:

// NOTE: can't do "while (file = [dirEnum nextObject]) {...} because that sets 
// file to an auto-released string that doesn't get released until after ALL
// iterations of the loop are complete. For large directories, that means our
// memory use spikes to hundreds of MBs. So we do this instead to ensure that
// the "file" string is released at the end of each iteration and our overall
// memory footprint stays low.

NSDirectoryEnumerator *dirEnum = [aFileManager enumeratorAtPath:someStartingPath];
BOOL keepRunning = YES;
while (keepRunning)
{
NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init];

NSString *file = [dirEnum nextObject];
if (file == nil) break;

// ... examine "file". Create a fileSystemItem object to represent this item.
// If it's a folder, we need to create a fileSystemItem for each item in the folder
// and each fileSystemItem's "parentItem" relationship needs to be set to the
// fileSystemItem we're creating right here for "file." How can I do this inside
// the directoryEnumerator, because as soon as we go to the next iteration of the
// loop (to handle the first item in "file" if "file" is a folder), we lose the
// reference to the fileSystemItem we created in THIS iteration of the loop for
// "file". Hopefully that makes sense...

[innerPool drain];
}

如果我编写一个递归函数来查看 startingPath 中的每个项目,并且如果该项目是一个文件夹,则在该文件夹上再次调用自身,依此类推,我可以了解如何构建模型。但是如何使用 NSDirectoryEnumerator 构建模型呢?我的意思是,据说这就是这个类存在的原因,对吗?

最佳答案

可以使用另一种目录枚举:

enumeratorAtURL:includePropertiesForKeys:options:errorHandler:

此枚举器具有其他有用的选项,并允许使用预取属性迭代 NSURL 实例,例如 NSURLNameKeyNSURLIsDirectoryKeyNSURLParentDirectoryURLKey 等。 ..它可以帮助摆脱递归的使用。

关于objective-c - 使用 NSDirectoryEnumerator 为文件系统建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7312092/

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