0

在运行我的线程一段时间后,Instruments显示__NSDate已稳步加入其#号活动值。线程中的iOS内存泄漏

我的结论是,这踩不分配物体。但是,这一行会导致编译错误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 ... 

} 

回答

5

的自动释放对象可能是为增加的内存使用情况, 的原因,但你不能用ARC使用NSAutoreleasePool。更换

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
// ... 
[pool drain]; 

@autoreleasepool { 
    // ... 
} 

更新:实际上,你需要在你的情况下,两个自动释放池。首先,在 Threading Programming Guide状态:

如果您的应用程序使用管理的内存模型,创建 自动释放池应该是你在你的线程进入 日常做的第一件事。同样,破坏这个自动释放池应该是你在线程中做的最后一件事。该池确保自动发布的对象被捕获,尽管直到线程 本身退出才释放对象。

而且最后一句话让你为什么需要另一个自动释放池线索:否则 在长时间运行的循环中创建的所有自动释放对象将只释放时 线程退出。所以,你必须

- (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 ... 
    } 
} 
+0

谢谢,我把它的内部,而循环,怎么样代码前,在此之后,我将有整体功能和第二autoreleasepool我while循环中的一个autoreleasepool块? – michael

+1

@michael:我最后的评论其实是错的,你需要两个池。我已经相应地更新了答案。 –

0
- (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 ... 

    } 
} 
+0

但是,在循环过程中没有清理NSDate对象,只有在方法结束后,我不得不在循环内放入它,是否可以? – michael

+0

您可以拥有多个自动释放池,并尽可能快地在想要释放临时对象的位置使用它们。请注意,在自定义线程中,整个线程至少需要一个池。 – simalone