karse23 karse23 - 4 months ago 72x
iOS Question

How to cancel or stop NSThread?

I'm doing an app that loads the contents of viewControllers using NSThread while is reading an XML file.

I have it done as follows:

// Some code...

[NSThread detachNewThreadSelector:@selector(loadXML) toTarget:self withObject:nil];
[super viewDidAppear:YES];


NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

// Read XML, create objects...

[pool release];

My problem is that I don't know how to stop the NSThread if the user changes to another viewController while the NSThread is loading, doing that the app crashes.

I've tried to cancel or exit the NSThread as follows but without success:

[NSThread cancel];
// or [NSThread exit];
[super viewDidDisappear:YES];

Can anyone help? Thanks.


When you detach new thread, you can no more cancel or exit it from viewDidDisappear etc. These UI specific methods execute only on main thread so the exit/cancel applies to the main thread which is obviously wrong.

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