Reputation: 1091
This is my searching function:
- (void)searchingMethod:(NSString *)aText{
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Entity" inManagedObjectContext:context];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate
predicateWithFormat:@"word LIKE %@",
[searchBar.text lowercaseString]];
[fetchRequest setPredicate:predicate];
//fetching array
NSLog(@"Place 1");
NSArray *wordArray = [context
executeFetchRequest:fetchRequest
error:nil];
NSLog(@"Place 2");
[self performSelectorOnMainThread:@selector(refreshTableView:)
withObject:wordArray waitUntilDone:NO];
NSLog(@"Searching End");
}
and I call the searching function with this method:
- (void)searchBar:(UISearchBar *) searchBar textDidChange:(NSString *)Tosearch{
if([[searchBar text] length] >0)
{
NSThread *aThread = [[NSThread alloc]
initWithTarget:self
selector:@selector(searchingMethod:)
object:searchBar.text];
[aThread start];
}
else
{
//others...
}
return;
}
Normally, I would get such result:
2012-07-05 00:04:46.706 MyApp[2376:207] Place 1
2012-07-05 00:04:46.783 MyApp[2376:207] Place 2
2012-07-05 00:04:46.823 MyApp[2376:207] searching End
After performed the searching method a dozen times, it stops at this position.
2012-07-05 00:11:42.174 MyApp[2376:207] Place 1
Continue to search several times, it returned to normal. And then odd again... It makes me puzzled.
I've spent many days to try different multi-thread methods, the result is still the same.
Please help me out! Thank you!
Upvotes: 0
Views: 863
Reputation:
Core Data is not thread safe. You need to create your own NSManagedObjectContext
on the background thread. With that you can do your searching in the background. You then cannot simply send the managed objects directly to the main thread. You have to ship the object IDs over and on the main thread get the objects for them from the main context using its objectWithID:
method.
Upvotes: 2