核心数据executeFetchRequest抛出NSGenericException(枚举时集合已变异) [英] Core Data executeFetchRequest throws NSGenericException (Collection was mutated while being enumerated)
问题描述
我正在使用Core Data开发一个iPhone应用程序。所有用户数据应与我们的服务器同步。为此,我创建了一个NSOperation女巫从我们的Web服务加载新数据的子类,并创建相应的托管对象。为了保持它们之间的关系,每个对象都使用remoteID(这是关系服务器数据库的主键)传输。
I'm developing a iPhone app with Core Data. All user data should be synchronized with our servers. For this purpose I created a subclass of NSOperation witch loads new data from our web service and creates corresponding managed objects. To maintain the relationships between them, every object is transmitted with a remoteID (which is the primary key of the relational server DB).
我们假设有两个受管对象:部门< - >>员工。同步的操作如下:
Let's say there are two managed objects: Department <-->> Employee. The synchronization works as follows:
-
从服务器加载所有部门。对于每个部门:创建一个Department对象并设置其remoteID。
Load all departments from server. For each department: create a Department object and set its remoteID.
从服务器加载所有员工。对于每个雇员:创建Employee对象,获取相关部门(通过remoteID)并将其分配给员工。
Load all employees from server. For each employee: create Employee object, fetch the related Department (by remoteID) and assign it to the employee.
获取部门会导致以下异常:
Fetching a department leads to the following exception:
*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSCFSet: 0x69c8a10> was mutated while being enumerated.<CFBasicHash 0x69c8a10 [0x2d6d380]>{type = mutable set, count = 1424,
entries => <A list of all newly created entities>
*** Call stack at first throw:
0 CoreFoundation 0x02d04919 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x02e525de objc_exception_throw + 47
2 CoreFoundation 0x02d043d9 __NSFastEnumerationMutationHandler + 377
3 CoreData 0x026225d0 -[NSManagedObjectContext executeFetchRequest:error:] + 4400
4 myApp 0x00059de4 +[AppFactory departmentWithRemoteID:inManagedObjectContext:] + 259
异常不会每次都抛出。将代码移动到主线程解决了问题。我不知道有什么问题。我在同步线程中创建了一个新的NSManagedObjectContaxt,并通过其NSManagedObjectID传递所有托管对象。
The exception isn't thrown every time. Moving the code to the main thread resolves the problem. I have no idea what's wrong. I created a new NSManagedObjectContaxt in the synchronization thread and passed all managed objects by its NSManagedObjectID.
任何想法?
推荐答案
我有同样的问题...
它被解决,因为我使用managedObjectContext在主线程上创建的后台线程。
解决方案是在后台线程上创建一个不同的ManagedObjectContext,并使用正则persistentStoreCoordinator ...
后它工作得很好!
I had the same problem... It was solved because I was using the managedObjectContext that was created on the main thread on a background thread. The solution was to create a different ManagedObjectContext on the background thread, and use the regular persistentStoreCoordinator... it worked fine after that!
这篇关于核心数据executeFetchRequest抛出NSGenericException(枚举时集合已变异)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!