0

I am creating a new Thread which runs one of my method: Now what i am doing is as follows:

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(myThreadFunc) object:nil];
[thread start];

in myThreadFunc

{
     while(isRunning){
         [self updateSomething];
         [NSThread sleepForTimeInterval:3.0];
     }
     NSLog(@"out");
}

In another func,i set isRunning = NO and thread = nil or [thread cancel] but myThreadFunc is sleeping so thread cannot exit. How can i control this case? Thanks so much.

The Bird
  • 397
  • 2
  • 8
  • 19

1 Answers1

1

Don't use a thread. Use a timer. If the something is expensive, dispatch it off to some queue other than the main queue and set some state variable to show it's still running (if the something isn't meant to run concurrently). Then, just cancel your timer. A simple example of the timer call-back function might be:

- (void)doSomething:(NSTimer*)timer
{
  // this assumes that this "something" only ever
  // runs once at a time no matter what, adjust this
  // to an ivar if it's per-class instance or something
  static BOOL alreadyDoingSomething = NO;
  if( alreadyDoingSomething ) return;
  alreadyDoingSomething = YES;
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self updateSomething];
    alreadyDoingSomething = NO;
  });
}

Now, if you simply cancel the timer, this will stop running. When you're ready to start it again, schedule a new timer with this method as the designated selector. To make this behave similar to your example above, you might set the timer interval to three seconds.

Jason Coco
  • 77,985
  • 20
  • 184
  • 180