tags:

views:

48

answers:

1

Hi

I am a bit uncertain on how to do this:

I start a "worker-thread" that runs for the duration of my apps "life".

[NSThread detachNewThreadSelector:@selector(updateModel) toTarget:self withObject:nil];

then

- (void) updateModel {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    BackgroundUpdate *update = [[BackgroundUpdate alloc] initWithTimerInterval:5];
    [[NSRunLoop currentRunLoop] run];   //keeps it going 'forever'
    [update release];
    [pool release];
}

Now the thread "wakes" up every 5 seconds(initWithTimerInterval) to see if there are any tasks it can do. All the tasks in the BackGroundUpdate Class are only time dependent for now. I would like to have a few that were "event dependent". e.g. I would like to call the Background Object from my main thread and tell it to "speedUp", "slowDown", "reset" or any method on the object.

To do this I guess I need something like performSelectorOnThread but how to get a reference to the NSthread and the Background Object?

+1  A: 

Direct answer: Instead of +[NSThread detachNewThreadSelector:toTarget:withObject:], use [[NSThread alloc] initWithTarget:selector:object:]. Don't forget to call -start!

Other thoughts:

  • Consider using NSOperation/NSOperationQueue instead. Easier and more efficient for most worker thread uses.
  • Consider whether you really need to do that periodic check on a background thread. Could you just do it on the main run loop, and then throw off work onto other threads as needed? Threads aren't free.
  • Consider whether polling is the best implementation, too. Look into NSCondition and/or NSConditionLock for more efficient ways to wake up threads when something happens (like adding work to a queue), no polling necessary.
bdrister
Thanks, bdrister.I have ended up using NSOperation for a lot of stuff lately, it takes a bit of getting used to but it really pays off. So complicated stuff where it can be justified = Subclass NSoperation, simple one-time stuff detach or performSelector.Thanks again.
RickiG