How to cancel or stop NSThread?

karse23 picture karse23 · Sep 13, 2011 · Viewed 9.3k times · Source

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:

-(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 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:

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

Can anyone help? Thanks.

Answer

Swapnil Luktuke picture Swapnil Luktuke · Sep 13, 2011

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..