CoreData多线程安全

时间:2023-03-10 00:44:43
CoreData多线程安全

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

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

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

CoreData多线程安全

  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);

//            }

//

//        }];