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.
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
}
}
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
isCancelledproperty isYES. If so, return without the update.[NSThread currentThread]should return your thread while you are insidepopulateDataInBackground