How to cancel or stop NSThread?

I am making an application that loads the contents of viewControllers using NSThread when it reads an XML file.

I did it as follows:

-(void)viewDidAppear:(BOOL)animated { // Some code... [NSThread detachNewThreadSelector:@selector(loadXML) toTarget:self withObject:nil]; [super viewDidAppear:YES]; } -(void)loadXML{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Read XML, create objects... [pool release]; } 

My problem is that I do not know how to stop NSThread if the user switches to another viewController while NSThread is loading, which causes the application to crash.

I tried to cancel or exit NSThread as follows, but without success:

 -(void)viewsDidDisappear:(BOOL)animated{ [NSThread cancel]; // or [NSThread exit]; [super viewDidDisappear:YES]; } 

Can anyone help? Thanks.

+4
source share
4 answers

When you disconnect a new stream, you can no longer cancel it or exit viewDidDisappear, etc. These UI-specific methods are executed only in the main thread, so the exit / cancel is applied to the main thread, which is clearly erroneous.

Instead of using the detach new thread method, declare the NSThread variable in .h and initialize it with the initWithTarget: selector: object: method and cancel it whenever you want ...

+7
source

You can also use the [NSThread exit]; method [NSThread exit]; NSThread .

+1
source

It is better to resolve the end of the stream gracefully, i.e. reach your natural completion if you can. It seems that in your case you can afford it. Also make sure that you are updating the user interface from the main thread and not from the secondary thread, since UIKit not thread safe.

0
source

You wrote: ... the application stops responding until the thread ends ...

Once you mark a thread for cancellation or exit, you need to manually stop everything that was caused by the thread. Example: ....

 - (void) doCalculation{ /* Do your calculation here */ } - (void) calculationThreadEntry{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSUInteger counter = 0; while ([[NSThread currentThread] isCancelled] == NO){ [self doCalculation]; counter++; if (counter >= 1000){ break; } } [pool release]; } application:(UIApplication *)application - (BOOL) didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ /* Start the thread */ [NSThread detachNewThreadSelector:@selector(calculationThreadEntry) toTarget:self withObject:nil]; // Override point for customization after application launch. [self.window makeKeyAndVisible]; return YES; } 

In this example, the loop is because the thread is in a no-cancel state.

0
source

All Articles