Objective-C - 取消线程? [英] Objective-C - Canceling a thread?

查看:67
本文介绍了Objective-C - 取消线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个搜索功能,用户在textField中输入,随着文本的更改,我正在搜索本地数据库并在表格中填充数据。

I have a search function in my app where the user types in the textField, and as the text changes I am searching the local database and populating data in a table.

搜索可能需要1到10秒,具体取决于输入的文本,所以我决定使用一个线程。每次文本更改我想取消线程(如果已经运行),并使用new关键字再次启动它。问题是根据文档调用取消不保证线程将被杀死。那么这里的解决方案是什么?

The search might take anywhere between 1 to 10 seconds depending on the text entered, so I decided to use a thread. Every time the text changes I want to cancel the thread (If running already), and start it again with the new keyword. The problem is that according to the documentation calling cancel doesn't guaranty that the thread will be killed. So what is the solution here?

有没有办法杀死一个线程?

Is there any way to kill a thread?

- (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 属性是否。如果是这样,请在没有更新的情况下返回。

You don't want the thread to die necessarily, as it will be reused later (making threads is expensive). What you should do is break your work into as many pieces as you can, and in between each piece check to see if your thread's isCancelled property is YES. If so, return without the update.

[NSThread currentThread] 应该在你内部时返回你的线程 populateDataInBackground

[NSThread currentThread] should return your thread while you are inside populateDataInBackground

这篇关于Objective-C - 取消线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆