如何取消或停止NSThread?

我正在做一个应用程序,它在读取XML文件时使用NSThread加载viewControllers的内容。

我做到如下:

-(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时更改为另一个viewController,我不知道如何停止NSThread,这样做应用程序崩溃了。

我试图取消或退出NSThread如下,但没有成功:

 -(void)viewsDidDisappear:(BOOL)animated{ [NSThread cancel]; // or [NSThread exit]; [super viewDidDisappear:YES]; } 

有人可以帮忙吗? 谢谢。

当您分离新线程时,您无法再从viewDidDisappear等取消或退出它。这些特定于UI的方法仅在主线程上执行,因此退出/取消适用于主线程,这显然是错误的。

而不是使用分离新线程方法,在.h中声明NSThread变量并使用initWithTarget: selector: object:方法初始化它并随时随地取消它…

你也可以使用[NSThread exit]; NSThread方法。

如果可以的话,最好让线程优雅地结束,即达到其自然结论。 这听起来像你的情况,你可以负担得起。 还要确保您正在从主线程而不是辅助线程更新用户界面,因为UIKit不是线程安全的。

您写道:…该应用程序在线程完成时停止响应…

标记用于取消或退出的线程后,必须手动停止调用该线程的任何操作。 一个例子: ….

 - (void) doCalculation{ /* Do your calculation here */ } - (void) calculationThreadEntry{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSUInteger counter = 0; while ([[NSThread currentThread] isCancelled] == NO){ [self doCalculation]; counter++; if (counter >= 1000){ break; } } [pool release]; } application:(UIApplication *)application - (BOOL) didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ /* Start the thread */ [NSThread detachNewThreadSelector:@selector(calculationThreadEntry) toTarget:self withObject:nil]; // Override point for customization after application launch. [self.window makeKeyAndVisible]; return YES; } 

在该示例中,循环以线程处于未取消状态为条件。