加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 如何优化目录列表? (enumeratorAtPath和递归调

发布时间:2020-12-16 09:36:26 所属栏目:百科 来源:网络整理
导读:我编写了一个方法(getDirTree1),它使用推荐的类NSDirectoryEnumerator和方法nextObject从根目录列出所有目录.但是当它运行不可接受时使用了大量内存(主要是私有类NSPathStore2): -(void) getDirTree1:(NSString*)directoryPath { NSDirectoryEnumerator *di
我编写了一个方法(getDirTree1),它使用推荐的类NSDirectoryEnumerator和方法nextObject从根目录列出所有目录.但是当它运行不可接受时使用了大量内存(主要是私有类NSPathStore2):

-(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 /保留一些对象)以及如何做得更好.
谢谢.

解决方法

[directoryPath stringByAppendingPathComponent:filePath];返回一个自动释放的对象.由于它发生在这样一个紧密的循环中,所有这些对象都在加起来并导致大量的内存占用.你需要做的就是更频繁地摆脱它们.您可以将方法更改为不使用自动释放的方法,或者您可以创建自己的紧密自动释放池,如下所示:

while ( ( filePath = [ dirEnum nextObject ] ) != nil ) {
    NSAutoreleasePool* pool = [NSAutoreleasePool new];
    fullFilePath = [ directoryPath stringByAppendingPathComponent:filePath ];
    NSLog( @"%@ n",fullPath );
    [pool drain];
}

这将确保在您不再需要时立即释放所有内容,从而避免在循环期间堆积对象.

(有趣的旁注:NSPathStore2是一个与NSString(它是一个类集群)相关的私有类,用于存储路径类型的字符串.这就是我知道哪种方法有问题的方法.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读