CoreData中的NSManagedObjectContext在多线程中不安全,如果想要多线程访问CoreData的话,最好的方法是一个线程一个NSManagedObjectContext,

,每个NSManagedObjectContext对象实例都可以使用同一个NSPersistentStoreCoordinator实例,这个实例可以很安全的顺序访问永久存储,这是因为NSManagedObjectContext会在便用NSPersistentStoreCoordinator前上锁。

ios5.0为NSManagedObjectContext提供了initWithConcurrentcyType方法,其中的一个NSPrivateQueueConcurrencyType,会自动的创建一个新线程来存放NSManagedObjectContext而且它还会自动创建NSPersistentStoreCoordinator,AppDelegate和前一章的一样,ios5.0之前的可以用GCD来实现

  1. - (IBAction)addIntoDataSource:(id)sender {
  2. //    User* user=(User *)[NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.myAppDelegate.managedObjectContext];
  3. //    [user setName:_nameText.text];
  4. //    [user setAge:[NSNumber numberWithInteger:[_ageText.text integerValue]]];
  5. //    [user setSex:_sexText.text];
  6. //
  7. //    Address* address=(Address *)[NSEntityDescription insertNewObjectForEntityForName:@"Address" inManagedObjectContext:self.myAppDelegate.managedObjectContext];
  8. //    [address setIdentify:[NSNumber numberWithInteger:[_identyText.text integerValue]]];
  9. //    [address setHomelocation:@"咸宁"];
  10. //    NSError* error;
  11. //    BOOL isSaveSuccess=[_myAppDelegate.managedObjectContext save:&error];
  12. //    if (!isSaveSuccess) {
  13. //        NSLog(@"Error:%@",error);
  14. //    }else{
  15. //        NSLog(@"Save successful!");
  16. //    }
  17. NSManagedObjectContext* context=[[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
  18. //    context.parentContext=_myAppDelegate.managedObjectContext;
  19. [context performBlock:^{
  20. //background thread
  21. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mocDidSaveNotification:) name:NSManagedObjectContextDidSaveNotification object:nil];
  22. User* user=(User *)[NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.myAppDelegate.managedObjectContext];
  23. [user setName:_nameText.text];
  24. [user setAge:[NSNumber numberWithInteger:[_ageText.text integerValue]]];
  25. [user setSex:_sexText.text];
  26. NSError* error;
  27. if (![context save:&error]) {
  28. NSLog(@"Error is %@",error);
  29. }
  30. //        //main thread
  31. //        [_myAppDelegate.managedObjectContext performBlock:^{
  32. //            NSError* error;
  33. //            if (![_myAppDelegate.managedObjectContext save:&error]) {
  34. //                NSLog(@"error is %@",error);
  35. //            }
  36. //
  37. //        }];
  38. }];
  39. //    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  40. //
  41. //        dispatch_sync(dispatch_get_main_queue(), ^{
  42. //
  43. //        });
  44. //    });
  45. }

通知中心

  1. -(void)mocDidSaveNotification:(NSNotification *)notification
  2. {
  3. NSManagedObjectContext* saveContext=[notification object];
  4. if (_myAppDelegate.managedObjectContext==saveContext) {
  5. return;
  6. }
  7. if (_myAppDelegate.managedObjectContext.persistentStoreCoordinator!=saveContext.persistentStoreCoordinator) {
  8. return;
  9. }
  10. dispatch_sync(dispatch_get_main_queue(), ^{
  11. [_myAppDelegate.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
  12. });
  13. }

其实也可以不用通知就是把 下面的内容不让其注释,同时注释通知中心就行了

//    context.parentContext=_myAppDelegate.managedObjectContext;

//        //main thread

//        [_myAppDelegate.managedObjectContext performBlock:^{

//            NSError* error;

//            if (![_myAppDelegate.managedObjectContext save:&error]) {

//                NSLog(@"error is %@",error);

//            }

//

//        }];

CoreData多线程安全的更多相关文章

  1. 【CoreData】parent-child关系ManagedObjectContext应用

    当我们一开始使用CoreData框架和唯一的MOC进行应用的数据持久化的时候,如果创建项目的时候选择了“使用CoreData”,这会是XCode自动生成的模板代码的样子. 同时,配合NSFetched ...

  2. coreData详解

    1.初识CoreData CoreData的结构构成: NSManagedObjectModel的构成: 可以通过Entity创建继承自NSManagedObject类的文件,这个文件就是开发中使用的 ...

  3. 认识CoreData-多线程

    CoreData使用相关的技术点已经讲差不多了,我所掌握的也就这么多了.... 在本篇文章中主要讲CoreData的多线程,其中会包括并发队列类型.线程安全等技术点.我对多线程的理解可能不是太透彻,文 ...

  4. CoreData和SQLite多线程访问时的线程安全

    关于CoreData和SQLite多线程访问时的线程安全问题 数据库读取操作一般都是多线程访问的.在对数据进行读取时,我们要保证其当前状态不能被修改,即读取时加锁,否则就会出现数据错误混乱.IOS中常 ...

  5. 在多线程环境中使用CoreData

    在多线程环境中使用CoreData BY 子非鱼 · 2014 年 10 月 13 日   上回书说道,其实CoreData学起来也没有很复杂,我们其实增删改查都和别的ORM大同小异.但是世界总是很复 ...

  6. 关于CoreData和SQLite多线程访问时的线程安全问题

    数据库读取操作一般都是多线程访问的.在对数据进行读取时,我们要保证其当前状态不能被修改,即读取时加锁,否则就会出现数据错误混乱.IOS中常用的两种数据持久化存储方式:CoreData和SQLite,两 ...

  7. CoreData和SQLite多线程访问时的线程安全问题

    数据库读取操作一般都是多线程访问的.在对数据进行读取时,我们要保证其当前状态不能被修改,即读取时加锁,否则就会出现数据错误混乱.IOS中常用的两种数据持久化存储方式:CoreData和SQLite,两 ...

  8. Coredata中的多线程

    =================== 疑问: 1.coredata是什么?结构 2.如果在简单的demo中,我们可以在主线程中使用coredata.但是如果在真正的大项目中,这样可行么? 3.假设都 ...

  9. 多线程操作Coredata(转)

    第一步:搭建 Core Data 多线程环境这个问题首先要解决的是搭建 Core Data 多线程环境.Core Data 对并发模式的支持非常完备,NSManagedObjectContext 的指 ...

随机推荐

  1. scrum 4.0

    1.准备看板. 形式参考图4. 2.任务认领,并把认领人标注在看板上的任务标签上. 先由个人主动领任务,PM根据具体情况进行任务的平衡. 然后每个人都着手实现自己的任务. 3.为了团队合作愉快进展顺利 ...

  2. wiredtiger - hazard pointers

    http://www.drdobbs.com/lock-free-data-structures-with-hazard-po/184401890 memory deallocation  lock- ...

  3. STL(1)

    这一篇因为游戏设计而写的,里面采用了STL,先借用一下,过段时间专项研究. 模板 模板就是一种通用化的类,同一种模板可以创建无数种具有共同特征的容器类型.首先需要指定基础类型,比如int ,char, ...

  4. HTML之DOM

    对于B/S开发,客户端与服务器端的交互是非常必要的,JavaScript的提出解决了很多问题,AJAX的提出也解决了异步通信的问题,更加为用户着想了.而DOM是其中非常基础的知识,在学习AJAX的同时 ...

  5. CPU相关知识---物理CPU数、物理核数、逻辑核数、逻辑CPU数 ?

    一.物理CPU数.物理核数.逻辑核数.逻辑CPU数 相互关系??? 物理CPU数 ---> 每个物理CPU对应物理核数 ---> (每个物理核数对应逻辑核数)物理CPU对应逻辑核数 --- ...

  6. 应用框架的设计与实现——.NET平台(10 授权服务.CodeAccessSecurityAttribute)

    以下内容转载自:http://blog.csdn.net/dongma_yifei/article/details/1533124 CodeAccessSecurityAttribute 是 Prin ...

  7. [DNX]解决dnu restore时找不到Newtonsoft.Json的问题

    在Mac上用最新版的dnx 1.0.0-beta5-11855进行dnu restore,出现下面的错误: System.IO.FileNotFoundException: Could not loa ...

  8. [MSSQL2012]CUME_DIST函数

    CUME_DIST函数以某列作为基准,计算其它行相对于基准行数据的比例.差距比例,比较容易理解 先看下测试数据 DECLARE @TestData TABLE(     ID INT IDENTITY ...

  9. 根据配置文件加载js依赖模块(JavaScript面试题)

    面试题目 根据下面的配置文件 module=[ {'name':'jquery','src':'/js/lib/jquery-1.8.3.js'}, {'name':'swfobject','src' ...

  10. JsRender for index 循环索引使用说明

    循环是模版引擎必不可少的一部分,而说起循环,会引出一个至关重要的因素:索引. 所谓索引,即循环次数,通过索引,可以获取当前循环是第几次. 如果读者阅读过官方文档,会见到如下获取索引的方式: data: ...