Reputation: 1394
I am trying to update table view from Core data like this:
dispatch_queue_t request_queue = dispatch_queue_create("com.myqueue.qu", NULL);
dispatch_async(request_queue, ^{
NSManagedObjectContext *parent = [[CoreDataManager instance] managedObjectContext];
NSManagedObjectContext *searchContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:parent.concurrencyType];
[searchContext setPersistentStoreCoordinator:[[CoreDataManager instance] persistentStoreCoordinator]];
NSArray * array = ...// receive array from CoreData, just select, there is no changes
if (array.count > 0) {
dispatch_async(dispatch_get_main_queue(), ^{
block(array);
});
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
block(nil);
});
}
});
dispatch_release(request_queue);
In block I do:
_tableViewData = [array mutableCopy];
[self.tableView reloadData];
But in:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
My obj:
MyObj *obj = _tableViewData[indexPath.row];
With nil fields. So obj is empty.
Edit:
I tried to search without creating 'searchContext', using parentContext and tableView updated ok, Is it correct way?
dispatch_queue_t request_queue = dispatch_queue_create("com.myqueue.qu", NULL);
dispatch_async(request_queue, ^{
NSManagedObjectContext *parent = [[CoreDataManager instance] managedObjectContext];
NSArray * array = ...// receive array from CoreData, using parent as search context
...
Upvotes: 0
Views: 404
Reputation: 119041
You can't pass managed objects between threads like that. If you want to run the search on a background thread you should pass the managed object ids back to the table view and have it access the managed objects from the main thread context using the ids. When you do the background fetch you can configure the fetch to return the ids instead of the full objects.
Upvotes: 1