0

I have a void method called 'startTask'.

On button click, I launch 'startTask' in the background as follows:

[self performSelectorInBackground:@selector(startTask) withObject:nil];

I want to cancel this process when a button is clicked, I cannot however figure out how to do this, can anyone please help?

Thanks in advance

Cristian
  • 6,765
  • 7
  • 43
  • 64
  • Sorry, I just realized you're calling `performSelectorInBackground` and not `performSelector`, which changes things quite a bit. – Vervious Jun 08 '12 at 23:05
  • Also, see http://stackoverflow.com/questions/4992472/how-to-stop-performing-selector-in-background and http://stackoverflow.com/questions/7702023/prevent-performselectorinbackground-from-running-twice – Vervious Jun 08 '12 at 23:11

1 Answers1

0

I would use NSOperation and NSOperationQueue. These allow for canceling. Threads require much more work for them to get the signal.

Edit-- for an example

Create a simple class that subclasses NSOperation

In your implementation implement a -(void)main(){ } method. This method is called when your operation is executed.

In the file that you want to launch it from create a member variable of NSOperationQueue.

When you want to launch your task create the operation and add it to the queue. it will operate asynchronously and you can cancel it.

Here is a question for iOS but I believe it should be the same for Cocoa NSOperation on the iPhone

Community
  • 1
  • 1
utahwithak
  • 6,235
  • 2
  • 40
  • 62
  • could you possibly post an example on how I would create and cancel an NSOperation? Thanks for your help – Cristian Jun 08 '12 at 22:07
  • thanks for your help, is there no way I can cancel the process called from performselectorinbackground? – Cristian Jun 08 '12 at 22:25
  • It is not possible to cancel threads in the sense that you mean – abruptly terminating them without their cooperation. You can only signal them that they should exit and code the task so that it frequently checks for that signal and gracefully terminate themselves. This is because a thread can be in the middle of modifying shared state or it could hold shared resources, like locks. If you terminate it abruptly from the outside, the shared state could be in a corrupted, half-modified state or the shared resources could end up permanently denied to the rest of your app. – Ken Thomases Jun 09 '12 at 03:18