views:

833

answers:

1

I have an iphone app, it run some thread to compute search. The search is made calling a time consuming function from a library.

I need to exit from the thread when the app is terminating, otherwise the thread continue to run and the search create problem when i reopen the app.

I tried to subscribe in the thread

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mainApplicationWillTerminate) name:@"UIApplicationWillTerminateNotification" object:nil];

And in mainApplicationWillTerminate

-(void)mainApplicationWillTerminate;
{
    [NSThread exit];
}

The problem is still present, any idea?

+1  A: 

As stated in the docs you should avoid using [NSThread exit]. In general, to avoid memory leaks and other disasters, a thread should never be stopped "from the outside". A thread should always exits by itself.

In your thread main loop you should check if the thread was cancelled:

if ([[NSthread currentThread] isCancelled]) {
    return;
}

To cancel it you call its "cancel" method from another thread.

In your case you should setup an application delegate (see UIApplicationDelegate)

- (void)applicationWillTerminate:(UIApplication *)application
{
    [myThread cancel];
}

Better have a look to the nice NSOperation class also.

IlDan
Missing a ']' on the right side of the if statement
Brock Woolf
fixed, thank you
IlDan
Hi, tnx for the responseI have a blocking time consuming function, if the thread call that function and i exit from the app but thread is still working, if i reopen the app it crash.I must to found a way to kill the thread before exit from mainThread
Luca Bartoletti
You shouldn't have blocking time consuming functions, particularly on the iPhone. Anyway in applicationWillTerminate you must cause the blocking function to exit. If you can't then you must rethink your coding solution.
IlDan