【发布时间】:2011-02-23 01:36:57
【问题描述】:
虽然在模拟器上似乎没有问题,但在设备上使用performSelectorInBackground 会导致内存泄漏。或者至少这就是 Instruments 所表明的。查看代码,我不知道原因可能是什么。
我试图将受影响的代码剥离到最低限度,但奇怪的是 Instruments 每次执行这段代码时都会显示泄漏。
这里有什么不寻常的地方吗?
//In viewcontrollerA:
-(void)mainLoop
{
[self.viewControllerB performSelectorInBackground:@selector(calculateTotals) withObject:nil];
//This gives the same problem
//[NSThread detachNewThreadSelector:@selector(calculateTotals) toTarget:self.viewControllerB withObject:nil];
//UI stuff ...
}
//viewControllerB:
-(void)calculateTotals
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//Heavy calculations ...
[pool release];
}
编辑: 我仍在调查这个问题,似乎泄漏是由于堆栈下方的某个地方 [NSThread start] 永远不会跟随 [NSThread exit]。因此,似乎偶尔会有一个线程一直在运行而从未结束它。 现在我的问题是,我能做些什么来手动结束那些“悬而未决”的威胁吗?
【问题讨论】:
-
Instruments 说什么样的对象被泄露了?
-
我的即兴猜测是它是从 performSelectorInBackground 保留它的目标的一个保留周期,这篇文章可能会有所帮助:mikeash.com/pyblog/…
-
@kperryua 它说泄漏来自“GeneralBlock-3584”,挖掘它揭示了负责任的调用是 -[NSThread start] 和 +[NSThread exit]。我真的无法编造这应该是什么意思?
标签: iphone objective-c cocoa multithreading memory