NSManagedObjectContext 已锁定
我的应用程序中有两个线程正在运行。
- 在主线程中,我更新实体中键的值或从核心数据获取一些行。
- 在后台线程中,我从服务器下载数据。
但有时在更新/处理 [managementObjectContextexecuteFetchRequest:request error:&error]
上的核心数据时
......我得到:
#0 0x34507c5c in semaphore_wait_signal_trap ()
#1 0x34507f58 in semaphore_wait_signal ()
#2 0x364d573a in pthread_mutex_lock ()
#3 0x35c91a2e in -[_PFLock lock] ()
#4 0x35c91a12 in -[NSPersistentStoreCoordinator lock] ()
#5 0x35c919e8 in -[NSManagedObjectContext(_NSInternalAdditions) lockObjectStore] ()
#6 0x35c90676 in -[NSManagedObjectContext executeFetchRequest:error:] ()
NSManagedObjectContext如何被锁定?为此我能做什么呢?
I have two threads operating in my app.
- In the Main thread I update values of keys in entities or gets some rows from Core Data.
- In the background thread I download data from a server.
But some times during update/processing on core data on [managedObjectContext executeFetchRequest:request error:&error]
… I get:
#0 0x34507c5c in semaphore_wait_signal_trap ()
#1 0x34507f58 in semaphore_wait_signal ()
#2 0x364d573a in pthread_mutex_lock ()
#3 0x35c91a2e in -[_PFLock lock] ()
#4 0x35c91a12 in -[NSPersistentStoreCoordinator lock] ()
#5 0x35c919e8 in -[NSManagedObjectContext(_NSInternalAdditions) lockObjectStore] ()
#6 0x35c90676 in -[NSManagedObjectContext executeFetchRequest:error:] ()
How does the NSManagedObjectContext get locked? What can I do for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
锁定是正常操作的一部分,并不是问题的根源。
最有可能的是,您在管理单独线程上的上下文时遇到问题。确保为每个线程使用不同的上下文,并确保不在线程之间传递托管对象。确保在尝试从另一个线程访问一个线程上所做的更改之前合并上下文。
The lock is part of the normal operation and is not the source of your problem.
Most likely, you have a problem managing the context on the separate threads. Make sure you use a different context for each thread and make sure you don't pass managed objects between the threads. Make sure you merge the contexts before trying to access changes made on one thread from another.
在多线程应用程序中掌握 CoreData 可能很困难。确保为每个使用 CoreData 的线程创建一个新的 NSManagedObjectContext。 MOC 必须在使用它的线程中创建。 MOC 本身不是线程安全的。 CoreData 不会为你锁定它。如果您为每个线程使用新的 MOC,则不必执行锁定。
在堆栈跟踪中,您可以看到 NSPersistentStoreCoordinator 已锁定(而不是 MOC)。 CoreData 这样做是为了使得只有一个 MOC 可以同时访问 NSPersistentStoreCoordinator。
Mastering CoreData in multithreaded apps can be difficult. Make sure you create a new NSManagedObjectContext for each thread that uses CoreData. The MOC must be created in the thread where it is used. The MOC itself is not thread safe. CoreData does not lock it for you. If you use a new MOC for each thread you don't have to do the locking.
In your stacktrace you can see that the NSPersistentStoreCoordinator is locked (not the MOC). CoreData does this so that only one MOC can access the NSPersistentStoreCoordinator at the same time.