我正在实施一些核心数据示例项目。我已经定义了一个mainManagedContext和一个privateManagedContext。
现在我的问题是,“如果我使用多个线程访问privateManagedContext,这是对的吗?”
提前谢谢。
答案 0 :(得分:0)
In my experience with accessing at the same time the static context lead me to a crashes.
So the only solution that I've implemented is to make a copy of the managedObjectContext for each tread where i have to work and make all my function( add/edit/save) with context as parameter:
so in some thread make a copy of context:
NSManagedObjectContext *localContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[localContext setPersistentStoreCoordinator:YourStaticManagedObjectContext.persistentStoreCoordinator];
and use that context in current thread (add/edit) then save context:
[YourManager saveContext:localContext withBlock:nil];
be careful if you need data at the same time when write in one thread and read on other thread better to implement some synchronized access to that staticManagedObjectContext.
答案 1 :(得分:0)
您需要参考本指南:
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/Concurrency.html
简而言之,您通常无法从多个线程引用相同的托管对象上下文。除非您相应地设置并发策略。但是,即使这样,你也不会真正实现并发I / O操作(这是因为并行I / O通常比较慢,除其他原因之外)。
你想做什么?