8877

Core Data : inserting Objects crashed in global queue [ARC - iPhone simulator 6.1]

I have a very simple Core Data demo, in which there is only one button.

When I click the 'run' button, the App creates 10,000 objects in a for-loop, which is <strong>running in the global queue</strong>.

<strong>Update for more detail : If I put the for-loop in main thread, it runs well.</strong>

<strong>Update for my intent : I know that MOC is not thread-safe, but according to the Apple doc, we can also use serial queue to access the MOC, and the serial queue uses more than one threads.</strong>

Here I create the Core Data stack:

#pragma mark - Core Data Stack - (NSManagedObjectContext *)managedObjectContext { if (nil != _managedObjectContext) { return _managedObjectContext; } _managedObjectContext = [[NSManagedObjectContext alloc] init]; if (self.persistentStoreCoordinator) { [_managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator]; } return _managedObjectContext; } - (NSManagedObjectModel *)managedObjectModel { if (nil != _managedObjectModel) { return _managedObjectModel; } _managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil]; return _managedObjectModel; } - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (nil != _persistentStoreCoordinator) { return _persistentStoreCoordinator; } NSString *storeType = NSSQLiteStoreType; NSString *storeName = @"model.sqlite"; NSURL *storeURL = [NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:storeName]]; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel]; NSError *error = nil; if (![_persistentStoreCoordinator addPersistentStoreWithType:storeType configuration:nil URL:storeURL options:nil error:&error]) { NSLog(@"Error : %@\n", [error localizedDescription]); NSAssert1(YES, @"Failed to create store %@ with NSSQLiteStoreType", [storeURL path]); } return _persistentStoreCoordinator; } #pragma mark - #pragma mark Application's Documents Directory - (NSString *)applicationDocumentsDirectory { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; return basePath; }

after app has launched :

@implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. if (self.managedObjectContext) { ; } return YES; }

When I click the button :

- (IBAction)runButtonDidClick:(id)sender { /** * Access the moc using different threads to make deadlock. */ [self runSave]; } - (void)runSave { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *moc = appDelegate.managedObjectContext; if (moc) { for (int j = 0; j < 10000; ++j) { People *people = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:moc]; people.name = @"noname"; } NSLog(@"**********IN SAVE %@", [NSThread currentThread]); NSError *error = nil; if ([moc save:&error]) { ; } NSLog(@"**********OUT SAVE %@", [NSThread currentThread]); } }); }

For clicking the run button some times, maybe 2 or 3 or 4... It crashes

I could not figure out why... Thanks for any help.

<img src="https://i.stack.imgur.com/wYng8.png" alt="enter image description here">

<img src="https://i.stack.imgur.com/9I673.png" alt="enter image description here">

Answer1:

Core data should be always work on thread witch have moc. the only job for performBlock and performBlockAndWait is that take care of thread safety. With it inserting to Core Data will always running in the right thread. You can define moc on whatever thread you want - performBlock always choose the right one.

So:

[self.managedObjectContext performBlock:^{ for(NSDictionary *dic in arr) { //inserting here! } }];

In your case:

- (void)runSave { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *moc = appDelegate.managedObjectContext; if (moc) { [moc performBlock:^{ for (int j = 0; j < 10000; ++j) { People *people = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:moc]; people.name = @"noname"; } NSError *error = nil; if ([moc save:&error]) { ; } }]; } }); }

Recommend

  • How to create sharable Core Data .sqlite backups locally and in iCloud using current NSPersistentSto
  • MFMailComposer not working in io6 landscape mode
  • Creating a file name by adding two NSStrings
  • ASIHTTPRequest memory leaks
  • How to save text field value in uicollectionviewcell
  • Load audio in DOCUMENTS when UITableView “cell” is pressed
  • Use two different cell identifier on same table view
  • Cells become empty after scrolling. (Xcode)
  • How to observe the value of an NSTextField
  • react native AsyncStorage firebase JSON value '' of type NSNull cannot be converted to NSS
  • NSBundle finds mp3 file but not m4a when trying to instantiate AVAudioPlayer
  • How can i get the locale from currency names list
  • CMCalibratedMagneticField doesn't update
  • Determining if a Unicode character is visible?
  • How to convert NSString to ASCII value from String Value
  • Best way to initialise / clear a string variable cocoa
  • Swipe Buttons in IOS 9 Remote Notification - Work when app in background not when app out of memory
  • NSURL Always Returns Nil
  • UITableView cell: selectedBackgroundView without showing backgroundView
  • Force lowercase - ios swift
  • How to load an NSDictionary from a file created with writeToFile?
  • I am trying to drop multiple pins on a map view but getting error
  • error with Xcode 6 'Duplicate interface definition for class 'ViewController'
  • NSDate isMemberOfClass: [NSDate class] returns false? [duplicate]
  • Display Local HTML file from documents directory in a UIWebView on iPhone
  • no @interface for 'UITableView' declares the selector 'initWithStyle:reuseIdentifiers
  • Loading huge Text file in UITextview crashes
  • adding zeros in objective-c string formats
  • Customizing NSLog Function on iPhone
  • using AVSystemController in iPhone App
  • Unable to add the file iOS application bundle
  • Display a .pdf in an iOS app without downloading it from the internet
  • How do I include superscripts in NSString?
  • bundle sqlite database with app and stringByAppendingPathComponent error
  • Objective-C – access extern const with a string containing its name? [duplicate]
  • Post comment to WordPress Blog from iPhone programmatically
  • iOS Date formatting
  • What is this iOS exception with NSCFType?
  • how to solve invalid conversion specifier warning in iphone app
  • Compare two NSDates in iPhone