NSEnumerator内存泄漏 [英] NSEnumerator memory leak

查看:76
本文介绍了NSEnumerator内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我使用枚举器的方式,这种泄漏像疯了似的.为什么?如果我不释放枚举器,它的泄漏会更加严重-我了解得很多..但我不明白为什么它仍然泄漏.

This leaks like mad, due to the way I use enumerators. Why? It leaks even more severely if I don't release the enumerator - I understand that much.. but I don't understand why this still leaks.

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

   // insert code here...
   NSLog(@"Hello, World!");

   // Create an array and fill it with important data!  I'll need to enumerate this.
   NSMutableArray *myArray = [[NSMutableArray alloc] initWithCapacity:300];

   int i;
   for(i = 0; i < 200; i++)
     [myArray addObject:[NSNumber numberWithInt:i]];

   while(1)
   {
      NSEnumerator *enumerator = [myArray objectEnumerator];
      // Imagine some interesting code here
      [enumerator release];
   }

   // More code that uses the array..

   [pool drain];
   return 0;
}

推荐答案

它本身不会泄漏-您不应该释放枚举器.

It doesn't leak, per se — and you shouldn't release the enumerator.

内存泄漏是指内存已分配但无法释放(通常是因为您不再有指向它的指针).在这种情况下,枚举器将在自动释放池耗尽时被释放,但是您要防止程序在循环中到达该行.这就是为什么枚举器堆积如山.如果将循环更改为:

A memory leak is when memory is left allocated but can no longer be released (typically because you no longer have a pointer to it). In this case, the enumerator will be released when the autorelease pool drains, but you're preventing the program from reaching that line with your loop. That's why the enumerators pile up. If you change the loop to:

while(1)
{
    NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init];
    NSEnumerator *enumerator = [myArray objectEnumerator];
    [innerPool drain];
}

您会发现您的内存消耗保持不变,因为枚举器将在每次迭代结束时正确释放.

you'll find that your memory consumption remains constant, because the enumerator will be properly released at the end of each iteration.

这篇关于NSEnumerator内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆