我試圖從給定的起始路徑建模文件系統的結構。目標是從該路徑開始創建文件系統的標準NSOutlineView
。使用NSDirectoryEnumerator建模文件系統
我有一個模型對象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
模型?我的意思是,據說這就是班級存在的原因,對吧?