CoreData多線程安全

CoreData中的NSManagedObjectContext在多線程中不安全,若是想要多線程訪問CoreData的話,最好的方法是一個線程一個NSManagedObjectContext,ios

,每一個NSManagedObjectContext對象實例均可以使用同一個NSPersistentStoreCoordinator實例,這個實例能夠很安全的順序訪問永久存儲,這是由於NSManagedObjectContext會在便用NSPersistentStoreCoordinator前上鎖。安全

     ios5.0爲NSManagedObjectContext提供了initWithConcurrentcyType方法,其中的一個NSPrivateQueueConcurrencyType,會自動的建立一個新線程來存放NSManagedObjectContext並且它還會自動建立NSPersistentStoreCoordinator,AppDelegate和前一章的同樣,ios5.0以前的能夠用GCD來實現多線程

 

[plain]  view plain copy print ?
  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.       
  40. //    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
  41. //         
  42. //        dispatch_sync(dispatch_get_main_queue(), ^{  
  43. //          
  44. //        });  
  45. //    });  
  46. }  

通知中心app

 

 

[plain]  view plain copy print ?
  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. }  


其實也能夠不用通知就是把 下面的內容不讓其註釋,同時註釋通知中心就好了 async

 

   

//    context.parentContext=_myAppDelegate.managedObjectContext;ide

 

  

//        //main threadoop

//        [_myAppDelegate.managedObjectContext performBlock:^{spa

//            NSError* error;.net

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

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

//            }

//            

//        }];

相關文章
相關標籤/搜索