类NSThread的对象自动释放,没有池到位

时间:2012-02-11 23:35:50

标签: objective-c multithreading

我正在使用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的内存管理。谁可以给我解释一下这个?非常感谢!

2 个答案:

答案 0 :(得分:2)

你需要一个线程池。

-(void)someMethod {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //code that should be run in the new thread goes here

    [pool release];
}

你也可以考虑使用弧线。 http://longweekendmobile.com/2011/09/07/objc-automatic-reference-counting-in-xcode-explained/

答案 1 :(得分:1)

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

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