由于我使用枚举数的方式,这就像是疯了一样。为什么?如果我不释放枚举器,它的泄漏会更严重--我明白这一点。但我不明白为什么这个还在泄露。
#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;
}发布于 2011-03-22 04:58:35
它本身不会泄漏--而且你不应该释放枚举器。
内存泄漏是指内存保持已分配状态,但不能再释放(通常是因为您不再有指向它的指针)。在这种情况下,枚举器将在自动释放池耗尽时释放,但您正在阻止程序使用您的循环到达该行。这就是为什么枚举数堆积起来的原因。如果将循环更改为:
while(1)
{
NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init];
NSEnumerator *enumerator = [myArray objectEnumerator];
[innerPool drain];
}您会发现内存消耗保持不变,因为枚举数将在每次迭代结束时正确释放。
发布于 2011-03-22 04:59:31
它的泄漏是因为你最外面的自动释放池只能做一次它的事情。在while(1)循环中创建的任何自动释放的对象都会一直占用内存,直到程序流到达最后的池排泄器。
要避免这种情况,请在循环中创建其他嵌套的自动释放池,如下所示:
while(1) {
NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init];
// .. Do a bunch of stuff that creates autoreleased objects
[innerPool drain];
}这种方法类似于AppKit的工作方式,通过其事件循环为每次迭代创建和排出一个新的自动释放池。
https://stackoverflow.com/questions/5383463
复制相似问题