有时候,我们需要有个worker thread来做一些密集型或者长耗时的任务,以避免阻塞住UI,给用户不好的体验。比如从网络上获取一批数据,然后解析它们,并将其输出到存储文件中。这时候,由于数据层发生了变动,我们希望通知到主线程更新UI —— 这就涉及到Core Data的多线程特性。
比如我们一直以来使用的Demo中,添加球员信息的AddPlayerViewController和显示球员列表的PlayerListViewController在进行CURD操作时都是在主ViewController的context中完成的,这通过维持一个属性cdViewController指向主ViewController来实现:
- #pragma mark -
- #pragma mark - UITableView Delegate
- - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
- {
- [tableView deselectRowAtIndexPath:indexPath animated:YES];
- Team *teamObject = [self.teamArray objectAtIndex:indexPath.row];
- PlayerListViewController *playerListVC = [[[PlayerListViewController alloc] init] autorelease];
- playerListVC.team = teamObject;
- playerListVC.cdViewController = self;
- [self.navigationController pushViewController:playerListVC animated:YES];
- }
- #pragma mark -
- #pragma mark - Player CURD
- - (void)addPlayer:(id)sender
- {
- AddPlayerViewController *addPlayerVC = [[[AddPlayerViewController alloc] init] autorelease];
- addPlayerVC.cdViewController = self.cdViewController;
- addPlayerVC.team = self.team;
- [self presentModalViewController:addPlayerVC animated:YES];
- }
对于比较小的Demo,这么写代码是可以接受的,虽然也会觉得传递得有点长。
当程序的代码规模比较大,或者说处理的数据比较多时,我们可以通过引入并发特性来做一点优化。
通过创建临时的context来添加球员信息:
- - (IBAction)addBtnDidClick:(id)sender
- {
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- NSManagedObjectContext *tmpContext = [[NSManagedObjectContext alloc] init];
- [tmpContext setPersistentStoreCoordinator:sharedPersistentStoreCoordinator];
- // We don't check the user input.
- Player *playerObject = [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectContext:tmpContext];
- playerObject.name = self.nameTextField.text;
- playerObject.age = [NSNumber numberWithInteger:[self.ageTextField.text integerValue]];
- playerObject.team = self.team;
- NSError *error = NULL;
- if (tmpContext && [tmpContext hasChanges] && ![tmpContext save:&error]) {
- NSLog(@"Error %@, %@", error, [error localizedDescription]);
- abort();
- }
- dispatch_async(dispatch_get_main_queue(), ^{
- [self dismissModalViewControllerAnimated:YES];
- });
- });
- }
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mocDidSaveNotification:) name:NSManagedObjectContextDidSaveNotification object:nil];
- - (void)mocDidSaveNotification:(NSNotification *)notification
- {
- NSManagedObjectContext *savedContext = [notification object];
- if (savedContext == self.managedObjectContext) {
- return ;
- }
- if (savedContext.persistentStoreCoordinator != self.persistentStoreCoordinator) {
- return ;
- }
- dispatch_async(dispatch_get_main_queue(), ^{
- NSLog(@"Merge changes from other context.\n");
- [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
- });
- }
- 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
- addPlayerVC.teamID = [self.team objectID];
- // ...
- playerObject.team = (Team *)[tmpContext objectWithID:self.teamID];
- 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.
- 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机制,可以参见这里。
相关推荐
Core Data is intricate, powerful, and necessary. Discover the powerful capabilities integrated into Core Data, and how to use Core Data in your iOS and OS X projects. All examples are current for OS X...
This book strives to give you clear guidelines for how to get the most out of Core Data while avoiding the pitfalls of this flexible and powerful framework. We start with a simple example app and ...
"Data Analytics with Hadoop: An Introduction for Data Scientists" ISBN: 1491913703 | 2016 | PDF | 288 pages | 7 MB Ready to use statistical and machine-learning techniques across large data sets? ...
What is Core Data? You'll hear a variety of answers to this question: It’s a database! It's SQLite! It's not a database! And so forth. Here's the technical answer: Core Data is an object graph ...
Core Data by Tutorials v4.0 Core Data by Tutorials v4.0
Core Data by Tutorials v4.0 Core Data by Tutorials v4.0
Core Data objc Core Data objc Core Data objc Core Data objc Core Data objc
Fully updated for Xcode 4.2, Pro Core Data for iOS explains how to use the Core Data framework for iOS SDK 5 using Xcode 4.2.
CHAPTER 2 THREE CORE PRINCIPLES FOR BUILDING A WINNING DATA STRATEGY CHAPTER 3 DATA IN, DATA OUT CHAPTER 4 THE FIVE SOURCES OF DATA-DRIVEN POWER CHAPTER 5 MAKING IT REAL FOR YOUR ORGANIZATION CHAPTER ...
The deep dive internal logic of core data in edgex foundry platform.
能够十分方便地为 Core Data 数据自动封装CRUD(创建,读取,更新和删除)操作。并且指定排序的域,可以自动为Core Data 数据加上按照这个域的排序操作。 Demo的演示了CRUD操作以及索引排序操作,比如自动为小编...
Core Data:Apple’s API for Persisting Data on Mac OS X,介绍mac osx下core data框架。
In this book, you'll master Core Data in iOS using Swift. Comprehensive coverage of Core Data, from beginner to advanced topics. Covers setting up a Core Data Stack, data modeling, versioning and ...
Mastering Core Data With Swift 英文mobi 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
Core.Data.Updated.for.Swift.3 學習 Swift 3 Core Data 必看書籍
Core Data in Objective-C Data Storage and Management for iOS and OS X(3rd) 英文无水印pdf 第3版 pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者...
Core Data是Mac OS X中Cocoa API的一部分,首次在Mac OS X 10.4 Tiger与iOS 3.0系统中出现[2]。它允许按照实体-属性-值模型组织数据,并以XML,二进制文件或SQLite数据文件的格式将其串行化。Core Data允许用户使用...
Core Data是Mac OS X中Cocoa API的一部分,首次在Mac OS X 10.4 Tiger与iOS 3.0系统中出现[2]。它允许按照实体-属性-值模型组织数据,并以XML,二进制文件或SQLite数据文件的格式将其串行化。Core Data允许用户使用...
Core Data是Mac OS X中Cocoa API的一部分,首次在Mac OS X 10.4 Tiger与iOS 3.0系统中出现[2]。它允许按照实体-属性-值模型组织数据,并以XML,二进制文件或SQLite数据文件的格式将其串行化。Core Data允许用户使用...
Core Data in Objective-C Data Storage and Management for iOS and OS X(3rd)