如何取消或停止NSThread? [英] How to cancel or stop NSThread?
问题描述
我正在做一个应用程序,它在读取XML文件时使用NSThread加载viewControllers的内容。
I'm doing an app that loads the contents of viewControllers using NSThread while is reading an XML file.
我完成了如下操作:
-(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];
}
我的问题是我不知道如何阻止NSThread用户在加载NSThread时更改为另一个viewController,这样做就会崩溃。
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.
我试图取消或退出NSThread,如下所示但没有成功:
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.
推荐答案
当您分离新线程时,您无法再从viewDidDisappear等取消或退出它。这些特定于UI的方法执行只在主线程上,所以退出/取消适用于主线程,这显然是错误的。
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.
而不是使用分离新线程方法,在.h中声明NSThread变量使用 initWithTarget:selector:object:
方法初始化它,并随时随地取消它..
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..
这篇关于如何取消或停止NSThread?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!