[英]iOS memory leak in thread
在運行我的線程一段時間后,Instruments顯示__NSDate一直在穩定其#生活價值。
我的結論是,這種花紋不會解除物體的作用。 但是,此行會導致編譯錯誤NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
如何強制該線程保留其所有對象,或者如何使用工作的ARC創建合適的線程。
- (void) start {
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(myThreadMainRoutine)
object:nil];
[myThread start]; // Actually create the thread
}
- (void)myThreadMainRoutine {
// stuff inits here ...
// Do thread work here.
while (_live) {
// do some stuff ...
[runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];
[NSThread sleepForTimeInterval:0.05f];
}
// clean stuff here ...
}
自動釋放的對象可能是內存使用增加的原因,但是您不能將NSAutoreleasePool
與ARC一起使用。 更換
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// ...
[pool drain];
同
@autoreleasepool {
// ...
}
更新:您的情況下實際上需要兩個自動釋放池。 首先,《 線程編程指南》指出:
如果您的應用程序使用托管內存模型,則創建自動釋放池應該是您在線程輸入例程中要做的第一件事。 同樣,銷毀此自動釋放池應該是線程中的最后一件事。 該池確保捕獲自動釋放的對象,盡管它直到線程本身退出才釋放它們。
最后一句話提供了為什么需要另一個自動釋放池的線索:否則,長時間運行的循環中創建的所有自動釋放對象僅在線程退出時才釋放。 所以你有了
- (void)myThreadMainRoutine {
@autoreleasepool {
// stuff inits here ...
while (_live) {
@autoreleasepool {
// do some stuff ...
[runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];
[NSThread sleepForTimeInterval:0.05f];
}
}
// clean stuff here ...
}
}
- (void)myThreadMainRoutine {
@autoreleasepool {
// stuff inits here ...
// Do thread work here.
while (_live) {
// do some stuff ...
[runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];
[NSThread sleepForTimeInterval:0.05f];
}
// clean stuff here ...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.