2012-02-11 58 views
2

我使用XCode4下列代码上的多线程工作:对象没有池自动释放到位

#import <Foundation/Foundation.h> 

bool trigger = false; 
NSLock *theLock=[NSLock new]; 

@interface Metronome : NSObject 
+(void)tick:(id)param; 
@end 

@implementation Metronome 
+(void)tick:(id)param{ 
while(1) 
    { 
      NSLog(@"TICK\n"); 
      usleep(1000000); 
      [theLock lock]; 
      trigger = true; 
      [theLock unlock]; 
    } 
} 
@end 

int main() 
{ 
    [NSThread detachNewThreadSelector:@selector(tick:) 
toTarget:[Metronome class] withObject:nil]; 
} 

没有编译错误,但在执行过程中控制台弹出如下警告:

objc[688]: Object 0x100300ff0 of class NSThread autoreleased with no pool 
in place - just leaking - break on objc_autoreleaseNoPool() to debug 

我不熟悉obj-C的内存管理。谁可以给我解释一下这个?非常感谢!

回答

1

你必须创建为每个线程NSAutoreleasePool需要调用autorelease包括主线程

int main() 
{ 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    [NSThread detachNewThreadSelector:@selector(tick:) 
toTarget:[Metronome class] withObject:nil]; 
    [pool release]; 
}