NSAutoreleasePool泄漏

时间:2011-01-19 15:42:07

标签: iphone objective-c

我知道这一定是我要忽视的简单事物,但为什么会出现这种情况:

//add a pool for this since it is on its own thread
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

//add the image
NSURL * imageURL = [NSURL URLWithString:[recipeData objectForKey:@"imagePath"]];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];
UIImageView * myImageView = [[UIImageView alloc] initWithImage:image];

//resize to make it fit the screen space 
CGRect frame = myImageView.frame;
frame.size.width = 320;
frame.size.height = 357;
myImageView.frame = frame;

[self.view addSubview:myImageView];


[activity stopAnimating];

[pool drain];
[self placeItems];

我收到错误:

_NSAutoreleaseNoPool():NSPathStore2类的对象0x4e2fdf0自动释放,没有池到位 - 只是泄漏

我尝试移动[游泳池排水]的位置,但没有做任何事情。在Google搜索原因时,我看到很多代码看起来都是这样的。

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

排空池具有释放并随后解除分配的效果,因为无法保留自动释放池。我怀疑在placeItems(或在[pool drain]之后调用的其他地方)中必须有一个autoreleasepool需要,因为此时池已经可以使用了。

所以,您可能想尝试评论排出消息,看看是否会导致泄漏消失。

答案 1 :(得分:2)

这里有很多话要说:

  • 首先,你正在泄漏myImageView。您必须在-addSubview
  • 之后发布它
  • 接下来,因为你在另一个线程上,你的[池排水]必须在最后
  • 最后,由于您不在主线程上,因此无法执行任何UI操作。尝试将[self.view addSubview:myImageView]替换为[self.view performSelectorOnMainThread:@selector(addSubview:) withObject:myImageView waitUntilDone:YES]。与[activity stopAnimating]相同。

和Brian说的一样,-drain消息必须在你的主题的末尾。