gpt4 book ai didi

iphone - NSOperation 和 CoreData 线程

转载 作者:太空狗 更新时间:2023-10-30 03:52:24 24 4
gpt4 key购买 nike

我正在使用 NSOperationQueue 在两个线程之间传递一些 NSManagedObject 数据,并发级别最大为 1,我想要一些关于我是否正确执行此操作的建议。

由于 NSManagedObject 不是线程安全的,我通过 NSOperation 派生类将 NSManagedObjectID 从 ThreadA(主线程)发送到 ThreadB。一般工作流程:

ThreadA (main thread):

  • creates NSPersistentStoreCoordinator

  • creates main NSManagedObjectContext(1)

  • creates NSManagedObjectContext(2) for use in workerThread

  • creates MyNSOperationItem, passes along NSManagedObjectContext and adds MyNSOperationItem to NSOperationQueue

ThreadB (NSOperationQueue's thread):

  • NSOperation derived class will retrieve data from the persistent
    store using the supplied objectID.

我的 NSOperation 类如下所示:

@interface MyNSOperationItem: NSOperation
{
// MyNSOperationItem is created in thread1 and MOC will be
// set on creation
NSManagedObjectContext *threadedMOC;

NSManagedObjectID *workItemObjectID;
}
@end

那么我的 NSOperation 派生类可以引用 NSManagedObjectContext 还是应该将第二个 NSManagedObjectContext 存储在其他地方?由于这是一个队列,因此将创建许多 MyNSOperationItem 实例,每个实例都指向同一个 NSManagedObjectContext。

最佳答案

我认为这应该可以满足您的所有需求:

http://developer.apple.com/mac/libra...reData/Articles/cdMultiThreading.html

如果您需要将抓取卸载到后台线程,这里是我上面引用的文档中的一个小提示:

Fetching in a Background Thread

One of the simplest multi-threading techniques you can use with Core Data to improve application responsiveness is to execute a fetch request on a background thread. (Note that this technique is only useful if you are using an SQLite store, since data from binary and XML stores is read into memory immediately on open.) This means that if a fetch is complicated or returns a large amount of data, you can return control to the user and display results as they arrive. For an example of how to do this, see the BackgroundFetching example in /Developer/Examples/CoreData/.

You use two managed object contexts associated with a single persistent store coordinator. You fetch in one managed object context on a background thread, and pass the object IDs of the fetched objects to another thread. In the second thread (typically the application's main thread, so that you can then display the results), you use the second context to fault in objects with those object IDs (you use objectWithID: to instantiate the object).

关于iphone - NSOperation 和 CoreData 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1725094/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com