如
WWDC 2014 session 225(核心数据新增内容)所述,iOS 8和OS X优胜美地的核心数据现在支持命令行参数-com.apple.CoreData.ConcurrencyDebug 1,以启用检测到违反Core Data的并发合同的断言.
在我的实验中,我发现它在iOS 8 beta 1(在设备和模拟器中)都可以工作,但是我似乎发现了一个错误的肯定,即框架是抛出一个多线程违规异常不这样做至少这是我的信仰.
问题:下面的代码是正确的还是我做的事情违反了Core Data的线程模型?
我所做的是设置一个非常简单的核心数据堆栈(使用内存存储,为了简单起见)与托管对象上下文名为backgroundContext与私有队列并发.然后我在该上下文中调用performBlockAndWait {},并在块中创建一个新的托管对象,将其插入上下文并保存.
保存操作是从Core Data获取多线程冲突异常的地方.
var backgroundContext: NSManagedObjectContext? func setupCoreDataStackAndViolateThreadingContract() { let objectModelURL = NSBundle.mainBundle().URLForResource("CoreDataDebugging",withExtension: "momd") let objectModel: NSManagedObjectModel? = NSManagedObjectModel(contentsOfURL: objectModelURL) assert(objectModel) // Set up a simple in-memory Store (without error handling) let storeCoordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: objectModel) assert(storeCoordinator) let store: NSPersistentStore? = storeCoordinator!.addPersistentStoreWithType(NSInMemoryStoreType,configuration: nil,URL: nil,options: nil,error: nil) assert(store) // Set up a managed object context with private queue concurrency backgroundContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) assert(backgroundContext) backgroundContext!.persistentStoreCoordinator = storeCoordinator! // Work on the background context by using performBlock: // This should work but throws a multithreading violation exception on // self.backgroundContext!.save(&potentialSaveError) backgroundContext!.performBlockAndWait { NSEntityDescription.insertNewObjectForEntityForName("Person",inManagedObjectContext: self.backgroundContext!) as NSManagedObject person.setValue("John Appleseed",forKey: "name") var potentialSaveError: NSError? // In the following line: EXC_BAD_INSTRUCTION in // `+[NSManagedObjectContext __Multithreading_Violation_AllThatIsLeftToUsIsHonor__]: let didSave = self.backgroundContext!.save(&potentialSaveError) if (didSave) { println("Saving successful") } else { let saveError = potentialSaveError! println("Saving Failed with error: \(saveError)") } } }
我已经在Objective-C中基本上测试了相同的代码,并得到相同的结果,所以我怀疑这是一个Swift的问题.
编辑:如果你想自己运行代码,那么I have put a project on GitHub(需要Xcode 6 / iOS 8 beta).
解决方法
苹果确认这是一个错误.它已经用Xcode 6 beta 4修复了.