From 9de46c99040c4a13ad977b06665d4a14239aee77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aleksandar=20Vaci=C4=87?= Date: Fri, 27 Sep 2013 22:28:38 +0200 Subject: [PATCH] Update DCTCoreDataStack.m Fixes a crash on startup in situation when two threads (two MOCs) attempt to access PSC while it's still being created. --- DCTCoreDataStack/DCTCoreDataStack.m | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/DCTCoreDataStack/DCTCoreDataStack.m b/DCTCoreDataStack/DCTCoreDataStack.m index ffd368c..2643520 100644 --- a/DCTCoreDataStack/DCTCoreDataStack.m +++ b/DCTCoreDataStack/DCTCoreDataStack.m @@ -160,8 +160,22 @@ - (NSManagedObjectContext *)rootContext { - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { - if (_persistentStoreCoordinator == nil) - [self _loadPersistentStoreCoordinator]; + if (_persistentStoreCoordinator != nil) + return _persistentStoreCoordinator; + + // This forces all threads that reach this + // code to be processed in an ordered manner on the main thread. The first + // one will initialize the data, and the rest will just return with that + // data. However, it ensures the creation is not attempted multiple times. + // from http://stackoverflow.com/questions/10388724/random-exc-bad-access-with-persistentstorecoordinator + if (![NSThread currentThread].isMainThread) { + dispatch_sync(dispatch_get_main_queue(), ^{ + (void)[self persistentStoreCoordinator]; + }); + return _persistentStoreCoordinator; + } + + [self _loadPersistentStoreCoordinator]; return _persistentStoreCoordinator; }