当前位置: 动力学知识库 > 问答 > 编程问答 >

objective c - Object of class NSThread autoreleased with no pool in place

问题描述:

I am working on multi-threading using the following codes in 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];

}

There is no compiling error, but during execution the console pops up the following warning:

objc[688]: Object 0x100300ff0 of class NSThread autoreleased with no pool

in place - just leaking - break on objc_autoreleaseNoPool() to debug

I'm not familiar with the memory management of obj-C. Can someone explain this to me? Thanks a lot!

网友答案:

you have to create a NSAutoreleasePool for every thread that need invoke autorelease include main thread

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

you need a thread pool.

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

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

    [pool release];
}

You could also considering using arc. http://longweekendmobile.com/2011/09/07/objc-automatic-reference-counting-in-xcode-explained/

分享给朋友:
您可能感兴趣的文章:
随机阅读: