`
dcj3sjt126com
  • 浏览: 1827716 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Core Data浅谈系列之八 : 关于并发

    博客分类:
  • IOS
阅读更多

有时候,我们需要有个worker thread来做一些密集型或者长耗时的任务,以避免阻塞住UI,给用户不好的体验。比如从网络上获取一批数据,然后解析它们,并将其输出到存储文件中。这时候,由于数据层发生了变动,我们希望通知到主线程更新UI —— 这就涉及到Core Data的多线程特性。

 
比如我们一直以来使用的Demo中,添加球员信息的AddPlayerViewController和显示球员列表的PlayerListViewController在进行CURD操作时都是在主ViewController的context中完成的,这通过维持一个属性cdViewController指向主ViewController来实现: 
  1. #pragma mark -   
  2. #pragma mark - UITableView Delegate  
  3.   
  4. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  
  5. {  
  6.     [tableView deselectRowAtIndexPath:indexPath animated:YES];  
  7.   
  8.     Team *teamObject = [self.teamArray objectAtIndex:indexPath.row];  
  9.     PlayerListViewController *playerListVC = [[[PlayerListViewController alloc] init] autorelease];  
  10.     playerListVC.team = teamObject;  
  11.     playerListVC.cdViewController = self;  
  12.     [self.navigationController pushViewController:playerListVC animated:YES];  
  13. }  
以及:
  1. #pragma mark -   
  2. #pragma mark - Player CURD  
  3.   
  4. - (void)addPlayer:(id)sender  
  5. {  
  6.     AddPlayerViewController *addPlayerVC = [[[AddPlayerViewController alloc] init] autorelease];  
  7.     addPlayerVC.cdViewController = self.cdViewController;  
  8.     addPlayerVC.team = self.team;  
  9.     [self presentModalViewController:addPlayerVC animated:YES];  
  10. }  
对于比较小的Demo,这么写代码是可以接受的,虽然也会觉得传递得有点长。
当程序的代码规模比较大,或者说处理的数据比较多时,我们可以通过引入并发特性来做一点优化。
 
通过创建临时的context来添加球员信息: 
  1. - (IBAction)addBtnDidClick:(id)sender  
  2. {  
  3.     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
  4.         NSManagedObjectContext *tmpContext = [[NSManagedObjectContext alloc] init];  
  5.         [tmpContext setPersistentStoreCoordinator:sharedPersistentStoreCoordinator];  
  6.   
  7.         // We don't check the user input.  
  8.         Player *playerObject = [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectContext:tmpContext];  
  9.         playerObject.name = self.nameTextField.text;  
  10.         playerObject.age = [NSNumber numberWithInteger:[self.ageTextField.text integerValue]];  
  11.         playerObject.team = self.team;  
  12.   
  13.         NSError *error = NULL;  
  14.         if (tmpContext && [tmpContext hasChanges] && ![tmpContext save:&error]) {  
  15.             NSLog(@"Error %@, %@", error, [error localizedDescription]);  
  16.             abort();  
  17.         }  
  18.   
  19.         dispatch_async(dispatch_get_main_queue(), ^{  
  20.             [self dismissModalViewControllerAnimated:YES];  
  21.         });  
  22.     });  
  23. }  
为了响应其它线程的变化,参考此文档,我们可以先监听消息,然后合并发生了的变化:
  1. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mocDidSaveNotification:) name:NSManagedObjectContextDidSaveNotification object:nil];  
  2.   
  3.   
  4. - (void)mocDidSaveNotification:(NSNotification *)notification  
  5. {  
  6.     NSManagedObjectContext *savedContext = [notification object];  
  7.   
  8.     if (savedContext == self.managedObjectContext) {  
  9.         return ;  
  10.     }  
  11.   
  12.     if (savedContext.persistentStoreCoordinator != self.persistentStoreCoordinator) {  
  13.         return ;  
  14.     }  
  15.   
  16.     dispatch_async(dispatch_get_main_queue(), ^{  
  17.         NSLog(@"Merge changes from other context.\n");  
  18.         [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];  
  19.     });  
  20. }  
这么做了之后,我们尝试添加一名球员,会得到如下错误信息:
[plain] view plaincopy
  1. 2013-01-21 09:56:08.300 cdNBA[573:617] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'team' between objects in different contexts  
这是由于我们把主线程context中的team对象传递到临时创建的context中进行操作了。在Core Data的多线程环境中,我们只能传递objectID或者重新fetch:
  1. addPlayerVC.teamID = [self.team objectID];  
  2.   
  3. // ...  
  4.   
  5. playerObject.team = (Team *)[tmpContext objectWithID:self.teamID];  
这样可以执行过去,控制台输出:
[plain] view plaincopy
  1. 2013-01-21 10:11:12.834 cdNBA[687:1b03] void _WebThreadLockFromAnyThread(bool), 0x83a91c0: Obtaining the web lock from a thread other than the main thread or the web thread. UIKit should not be called from a secondary thread.  
  2. 2013-01-21 10:11:12.932 cdNBA[687:c07] Merge changes from other context.  
第二行日志说明合并变化了,不过第一行告诉我们在非主线程里面访问了一些UI方面的东西。这是由于上面在global_queue里面访问了UITextField,把访问UI的代码提到外面即可。
 
BTW,在iOS 5以后,苹果提供了更为便捷有效的parent-child context机制,可以参见这里

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics