2011-09-05 60 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,等等。 ..它可以幫助擺脫遞歸使用。