Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 683
karse23 Avatar asked Sep 13 '11 11:09

karse23


2 Answers

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

like image 190
Swapnil Luktuke Avatar answered Nov 19 '22 21:11

Swapnil Luktuke


you can also use [NSThread exit]; method of NSThread.

like image 37
Maulik Avatar answered Nov 19 '22 22:11

Maulik