如何停止nsthread [英] how to stop nsthread
问题描述
我正在使用一个线程在我的应用程序中更新后台消息。该线程在我的消息类中启动。
I am using a thread to update messages in background in my application. The thread is started in my messages class.
Messages.m
timerThread = [[NSThread alloc] initWithTarget:self
selector:@selector(startTimerThread:) object:nil];
[timerThread start];
现在我希望线程在用户注销应用程序时停止。为了在signout方法(在另一个类中),我添加了
now I want the thread to stop when the user signout 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 signing out of the application the thread is still running.
推荐答案
(我假设你在程序中的其他地方创建了一个消息实例)
( I am assuming here that you create an instance of Messages somewhere else in the program )
根据您提供的代码,您将在注销过程中创建一个新的Messages实例(启动一个新线程),取消该新线程( - 取消是正确的方法停止一个线程 - 如果你的线程方法遵循文档中列出的注意事项),然后释放你的(额外?)消息实例。此时你的原始Messages实例仍然存在,并且其中的线程仍然在运行。
According to your provided code you are creating a new Messages instance as part of your sign out process ( which starts a new thread ), canceling that new thread ( -cancel is a proper way to stop a thread -- if your thread method follows the considerations listed in the documentation ), then releasing your ( extra? ) Messages instance. At this point your original Messages instance is still around, and the thread from that is still running.
如果你希望线程在类的实例被释放时停止,您可能应该在 - dealloc 方法,并确保在适当的时间释放原始的消息实例。
If you want the thread to stop when the instance of the class is deallocated, you probably should take care of that in a -dealloc method on Messages and make sure your original Messages instance is released at the proper time.
这篇关于如何停止nsthread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!