Reputation: 12559
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:
managedObjectContext
is currently fetching, what would happen to the allocation of fetchRequest
? Would I have a leak?Upvotes: 1
Views: 575
Reputation: 70956
Cocoa threading doesn't generally include the idea of forcing a thread to abort. You'll see a cancel
method, 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 in NSThread
and NSOperation
, for example. If the code doesn't check for a cancel request, the cancel
method 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?
Upvotes: 1