2011-09-05 61 views
1

我试图从给定的起始路径建模文件系统的结构。目标是从该路径开始创建文件系统的标准NSOutlineView使用NSDirectoryEnumerator建模文件系统

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

  • parentItem(指向另一fileSystemItem对象)
  • isLeafYES为文件; NO为文件夹)
  • childrenItems(其他fileSystemItems阵列)
  • fullPathNSString;对象的文件路径)

我的问题是:我如何使用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模型?我的意思是,据说这就是班级存在的原因,对吧?

回答

-2

如果该文件是一个目录,则需要创建一个新的目录枚举器; NSDirectoryEnumerator枚举一个目录,而不是系统上的每个目录。 所以是的,你将不得不使用递归。

0

它可以使用另一种目录列出:

enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:

此枚举有更多的有用的选项,并允许重复使用预取属性NSURL实例,如NSURLNameKeyNSURLIsDirectoryKeyNSURLParentDirectoryURLKey,等等。 ..它可以帮助摆脱递归使用。