2012-07-04 74 views
0

这是我的搜索功能:在后台线程搜索核心数据,功能终止随机

- (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"); 
} 

和我所说的搜索功能,用此方法:

- (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; 
} 

通常情况下,我会得到这样的结果:

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 

执行了十几次搜索方法后,停在这个位置。

2012-07-05 00:11:42.174 MyApp[2376:207] Place 1 

继续搜索多次,它恢复正常。然后再奇数... 这让我感到困惑。

我花了很多天尝试不同的多线程方法,结果仍然是一样的。
请帮我一把!谢谢!

+0

您是否在该后台线程上创建NSManagedContext'context'? –

+0

我已阅读Apple的文档[核心数据并发](http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/coredata/Articles/cdConcurrency.html#//apple_ref/doc/uid/ TP40003385-SW1),但不知道如何使用objectWithID创建NSManagedObjectContext: – Jimi

回答

2

核心数据不是线程安全的。您需要在后台线程上创建自己的NSManagedObjectContext。有了这个,你可以在后台进行搜索。然后您不能直接将托管对象直接发送到主线程。您必须在主线程上和主线程上运送对象ID,并使用其方法objectWithID:从主环境中获取对象。

+1

谢谢Sven!我修改了我的问题,并添加了创建NSManagedObjectContext的代码。我也尝试使用objectID创建NSManagedObjectContext,但失败了。你想给我看一些示例代码吗? – Jimi