Re: Newbie trying NSThread
Re: Newbie trying NSThread
- Subject: Re: Newbie trying NSThread
- From: Shawn Erickson <email@hidden>
- Date: Sun, 09 Apr 2006 10:19:25 -0700
On Apr 9, 2006, at 10:06 AM, Tom Watts wrote:
I need to create a second thread in my project to handle some work
without disturbing the rest of the app. I think what I am doing wrong
has to do with the run loop, but I just don't know. Here is what I
have going on. This thread needs to keep going until the app quits,
but it is going into the thread, and then the thread immediately dies.
#import "MyApp.h"
@implementation MyApp
- (IBAction)startAction:(id)sender
{
[NSThread detachNewThreadSelector:@selector(myNewThread:)
toTarget:self withObject:nil];
}
- (void)myNewThread:(id)sender
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSTimer *myTimer;
NSLog(@"In new thread");
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
do
{
NSLog(@"Starting timer in new thread");
// Do work here
}
while ( [[NSRunLoop currentRunLoop] runMode:NSModalPanelRunLoopMode
beforeDate:[NSDate distantFuture]] );
[myTimer release];
NSLog(@"Leaving new thread");
[pool release];
}
1) Runloops only run if they have registered sources otherwise they
just return. So you need to register your initial timer before you
first attempt to run the run loop. Registering a timer setups up a
timer event source on the current runloop.
2) Inside of your do/while loop you should release the current
autorelease pool and allocate a new one every time thru the loop.
-Shawn
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden