Reputation: 2350
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!
Upvotes: 2
Views: 1883
Reputation: 46598
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];
}
Upvotes: 1
Reputation: 6973
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/
Upvotes: 2