iPhone – How to Stop NSTHREAD

I am using a thread to update background messages in my application. The thread is started in my message class.

Messages.m

timerThread = [[NSThread alloc] initWithTarget:self
selector:@selector(startTimerThread:) object:nil];
[timerThread start];

Now I want the thread to stop when the user logs out of the application. For that in the signout method (in another class) I added

Messages *msg=[[Messages alloc]init]; 
[msg.timerThread cancel];
[msg release];

But even after exiting the application, the thread is still running .

(I assume you have created a message instance elsewhere in the program)

According to the code you provided, you are creating a new Messages instance as part of your logout process (starting a new thread), cancel the new thread (-cancel is a correct way to stop the thread – If your thread method follows the precautions listed in the document), then release your (extra?) message instance. At this time, your original Messages instance still exists, and the thread is still running.

< p>If you want to stop the thread when the instance of the class is released, you should probably handle Messages in the -dealloc method and make sure to release the original Messages instance at the appropriate time.

I am using a thread to update background messages in my application. The thread is started in my message class.

Messages.m

timerThread = [[NSThread alloc] initWithTarget:self
selector:@selector(startTimerThrea d:) object:nil];
[timerThread start];

Now I want the thread to stop when the user logs out of the application. For that in the signout method (in another class) I Added

Messages *msg=[[Messages alloc]init]; 
[msg.timerThread cancel];
[msg release];

But even after exiting the application, the thread is still running.

(I assume you created a message elsewhere in the program Example)

According to the code you provided, you are creating a new Messages instance as part of your logout process (starting a new thread), and canceling the new thread (-cancel is a kind of The correct way to stop the thread-if your threading method follows the precautions listed in the documentation), then release yours (extra? )Message instance. At this point, your original Messages instance still exists, and the thread is still running.

If you want to stop the thread when the instance of the class is released, you should probably use the -dealloc method Messages are processed and ensure that the original Messages instance is released at an appropriate time.

Leave a Comment

Your email address will not be published.