Alex Molskiy
Alex Molskiy

Reputation: 865

How to Terminate loop/thread

Here is part of my program. Loop in findDuplicates starts in background thread after button was pressed. Is there any way to stop/kill thread/loop by pressing another button?

- (IBAction)countDups:(id)sender {
   [self performSelectorInBackground:@selector(findDuplicates) withObject:nil];
}

-(void)findDuplicates
{
...
 for(int index=0;index<self.resultList.count;index++)
 { ... }
...
}

Upvotes: 1

Views: 950

Answers (2)

Parag Bafna
Parag Bafna

Reputation: 22930

You can return from background thread. create one member variable, initialize it with NO.

- (IBAction)countDups:(id)sender {
   mCancel = NO;
   [self performSelectorInBackground:@selector(findDuplicates) withObject:nil];
}

-(IBAction)stop
{
  mCancel = YES; //BOOL member variable;
}

-(void)findDuplicates
{
...
 for(int index=0;index<self.resultList.count;index++)
 { 
   If(mCancel)
   return; // return for thread to end

  ... }
...
}

Upvotes: 2

Alexander
Alexander

Reputation: 8147

Read up in the Threading Programming Guide under Terminating a Thread. performSelectorInBackground:withObject: essentially creates a new thread and runs the code on it.

Upvotes: 0

Related Questions