I want to make a CoreData fetch request on a background thread in order to give the user the option to cancel it.
Below is my background thread code:
- (void)searchDailyNotes
{
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"DailyNotes"
inManagedObjectContext:self.managedObjectContext];
NSString *searchString = [self.searchTextField stringValue];
NSFetchRequest *fetchRequest= [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate
predicateWithFormat:@"notes contains[cd] %@", searchString];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:predicate];
NSError *error = nil;
[_dailyNotesArray addObjectsFromArray:
[self.managedObjectContext
executeFetchRequest:fetchRequest
error:&error]];
NSLog(@"dailynotesArray count: %lu", [_dailyNotesArray count]);
if(error){
[NSApp presentError:error];
}
[fetchRequest release];
}
Questions:
- If the user wants to cancel the search, what would be the corrrect way to terminate the background thread?
- If I abort the thread while the
managedObjectContextis currently fetching, what would happen to the allocation offetchRequest? Would I have a leak?
Cocoa threading doesn’t generally include the idea of forcing a thread to abort. You’ll see a
cancelmethod, but that’s strictly advisory. The idea is that the code in the thread will check this state periodically and exit early if a cancel has been requested. You’ll see this inNSThreadandNSOperation, for example. If the code doesn’t check for a cancel request, thecancelmethod has no effect.Because of that, you’ll need to add checks for a cancel request if you want to handle cancellation. If you see that a cancel was requested, you can do whatever cleanup you need before actually finishing the thread. But you can’t interrupt the fetch request in progress anyway– once you’ve called the method to start it, you wait until it finishes.
On a separate note, how long do your fetches take that you actually need to worry about this situation?