Objective-C – 取消一个线程?

我有我的应用程序中的用户键入textField中的searchfunction,并且随着文本更改我正在search本地数据库并填充表中的数据。

根据input的文本,search可能需要1到10秒之间的时间,所以我决定使用一个线程。 每当文本改变,我想取消线程(如果已经运行),并用new关键字重新启动它。 问题是根据文档调用取消不保证线程将被杀死。 那么这里的解决scheme是什么?

有什么办法杀死一个线程?

- (void)populateData { if (self.searchThread.isExecuting) { [self.searchThread cancel]; } [self.searchThread start]; } - (void)populateDataInBackground { @autoreleasepool { // get data from db // populate table on main thread } } 

你不希望线程死掉,因为以后会重用(线程很贵)。 你应该做的是把你的工作分解成尽可能多的东西,然后在每件之间检查你的线程的isCancelled属性是否为YES 。 如果是这样,返回没有更新。

当你在populateDataInBackground里时, [NSThread currentThread]应该返回你的线程

我最终修改我的dataStorage,一次返回10个项目,只是为了testing。 我可能以后再用另一个号码。 这样我可以在我的while循环中退出线程。

另一个好处是,这样我可以填充表格,而不是等待所有的数据被检索。

 @interface ViewController @property (nonatomic, strong) NSthread *searchThread; @end @implementation ViewController @synthesize searchThread = _searchThread; - (void)populateData { [self.searchThread cancel]; self.searchThread = [[NSThread alloc] initWithTarget:self selector:@selector(populateDataInBackground) object:nil]; [self.searchThread start]; } - (void)populateDataInBackground { @autoreleasepool { [self.array removeAllObjects]; // I added paging functionality to my sql, so I get let's say 10 records at a time while (/*has data*/) { NSArray *arrayOf10 = [self.dataStorage getdatafromIndex:startingIndex withCount:10]; if ([[NSThread currentThread] isCancelled]) [NSThread exit]; [self.array addObjects:arrayOf10]; [self.tableView performSelectorOnMainThread:@Selector(reloadData) withObject:nil waitUntilDone:NO]; } } } @end 

其中一个可能的解决scheme将包括:

从主线程(例如“ searchNow ”)设置一些“ BOOL ”信号量/属性,并定期读取它,当你通过你的“ populateData ”后台线程/任务。

如果状态更改为“否”(假设“ searchNow ”== YES意味着该任务应该继续),则退出后台线程。