我寫了一個方法(getDirTree1),它使用建議的類NSDirectoryEnumerator和nextObject方法列出根目錄中的所有目錄。不過,雖然這是不可接受的運行使用大量的內存(主要是民營類NSPathStore2):如何優化目錄列表? (enumeratorAtPath和遞歸調用contentsOfDirectoryAtPath)
-(void) getDirTree1:(NSString*)directoryPath {
NSDirectoryEnumerator *dirEnum = [self->fileManager enumeratorAtPath:derectoryPath];
NSString *filePath;
NSString *fullFilePath;
while ((filePath = [ dirEnum nextObject ]) != nil) {
fullFilePath = [ directoryPath stringByAppendingPathComponent:filePath ];
NSLog(@"%@ \n", fullPath);
}
}
假設這是因爲對象NSDirectoryEnumerator,我重寫方法(getDirTree2)。現在使用遞歸方法,NSArray類和objectEnumerator方法。 但是再次使用了大量的內存。
-(void) getDirTree2:(NSString*)directoryPath {
NSArray *contents = [ self->fileManager contentsOfDirectoryAtPath:directoryPath error:NULL ];
NSEnumerator *enumeratorContent [ contents objectEnumerator ];
NSString *file;
BOOL fileIsDirectory = FALSE;
while ((file = [ enumeratorContent nextObject ])) {
NSLog(@"%@ \n", [ directoryPath stringByAppendingPathComponent: file ]);
if ([ self->fileManager fileExistAtPath:[ directoryPath stringByAppendingPathComponent:file ] isDirectory:&fileIsDirectory ] && fileIsDirectory)
[ self getDirTree2:[ directoryPath stringByAppendingPathComponent: file ] ];
}
}
我錯過了什麼(也許我必須dealloc /保留一些對象)以及如何做得更好。 謝謝。
會如何,如果自動引用計數是這樣進行正在使用? – newenglander
'@autoreleasepool {// code}' – andyvn22
謝謝,已經嘗試過了,也許我錯過了其他的東西。我會再試一次,如果它不起作用,我會發佈一個問題。 – newenglander