Re: Help with Timer
Re: Help with Timer
- Subject: Re: Help with Timer
- From: David Rio Vierra <email@hidden>
- Date: Wed, 1 Jan 2003 19:26:47 -1000
Before detaching your thread, store your main thread's current run loop
in an instance variable. Then you can just create your timer with the
+timerWith... methods instead of the +scheduledTimer... methods, and
add it to that runloop yourself from your second thread.
If your second thread involves a lot of heavy processing and/or a loop,
you might want to consider releasing and creating new
NSAutoreleasePools throughout so that autoreleased objects get released
and you don't eat up as much memory.
- Rio
sample code follows...
//instance var
NSRunLoop * mainThreadRunLoop;
- (void)awakeFromNib
{
forecast = [[Forecast alloc] init];
mainThreadRunLoop = [NSRunLoop currentRunLoop];
[NSTimer scheduledTimerWithTimeInterval:10 //seconds
target:self
selector:@selector(update:)
userInfo:nil
repeats:NO];
}
- (void)update:(NSTimer*)aTimer
{
[aTimer invalidate]; //removes aTimer from the run loop, which
releases it.
[NSThread detachNewThreadSelector:@selector(updateThread:)
toTarget:self withObject:self];
}
- (void)updateThread:(id)sender
{
NSAutoreleasePool* subpool = [[NSAutoreleasePool alloc] init];
[forecast update];
NSTimer * timer = [NSTimer timerWithTimeInterval:10 //seconds
target:self
selector:@selector(update:)
userInfo:nil
repeats:NO];
[mainThreadRunLoop addTimer:timer];
//note that with this, and with scheduledTimer, the timer is
retained by the run loop, and
//you don't need to retain unless you _really_ need it to stick
around after it's all done firing.
[subpool release];
}
On Wednesday, January 1, 2003, at 07:05 PM, Ted Lowery wrote:
Hi all-
I'm trying to create a process that will run periodically. I have the
process running in a separate thread, so that it doesn't block the
interface. It does some network accesses, and can take several seconds
to complete.
I've created a timer which I invalidate after it fires, and then I wish
to re-establish it after the thread completes. However, re-creating
the timer within the thread (and a separate NSAutoReleasePool) it never
fires. See code below...
[snip]
Any ideas?
Thanks, Ted
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.