ios - 如何在它自己的线程中使用核心数据?

标签 ios objective-c multithreading core-data

我正在制作一个与 9gag 应用程序非常相似的应用程序,并且我正在努力实现平滑滚动,所以我试图将所有内容都从主线程中删除。给我带来麻烦的是核心数据。

我有一个 PhotoSource 类,它创建自己的线程,如下所示:

@property (nonatomic) dispatch_queue_t photoSourceThread; <br/>... <br/>dispatch_async(self.photoSourceThread, ^{ ... });

我还有另一个类,它只处理核心数据:

@property (nonatomic, strong) TLCoreDataManager *coreDataManager;

PhotoSource 类中的一切都发生在它的线程内,包括对 TLCoreDataManager 的调用,如下所示:

dispatch_async(self.photoSourceThread, ^{
Photo *storedPhoto = [self.coreDataManager getPhotoWithURLString:urlString];
...
});

有时它可以工作,但在应用程序启动后,我从我的 NSFetchRequest[s] 中得到 0 个结果,我不知道该怎么做。任何想法可能是错误的?如果您需要更多代码,请告诉我!

谢谢

最佳答案

要在多线程环境中使用 CoreData 来改变您的数据并最终更新您的 GUI,您需要将更改合并到基于主队列的上下文(由基于核心数据的应用程序生成的默认代码中的默认上下文)。 我建议您使用获取结果 Controller 来监听对您的数据所做的更改。

你可以使用类似的东西:

/*!
 @see http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/CoreData/Articles/cdConcurrency.html
 */
- (void) doSomethingInBackgroundWithoutBlocking:(NSPersistentStoreCoordinator*)coordinator
{
    NSManagedObjectContext* bgContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    [bgContext setPersistentStoreCoordinator:coordinator];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(mergeChanges:) //merge to your main context
                                                 name:NSManagedObjectContextDidSaveNotification
                                               object:bgContext];
    [bgContext performBlock:^{
        //Do somethig with your persistent store data
        //Objects fetched here will only be available for this context
        //And on its own queue
        //Probably need to save & merge to main context so that the fetch results controller will be updated
        //remove the observer
    }];
}

关于ios - 如何在它自己的线程中使用核心数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15740330/

相关文章:

ios - UIImageView 中的动画 gif

objective-c - self.view.frame.size.height 在 iphone 4s 上返回 568 而不是 480

objective-c - 如何像事件监视器一样以编程方式检查 Mac 上的可用系统内存?

iphone - 为 MKAnnotation 设置图像

java - 多线程通信为什么使用等待和通知不能保证输出

c++ - 在 TCP 线程服务器 C++ 中传输文件

python - 如何使用线程中的数据?

objective-c - IB 的 GestureRecognizers 在模拟内存警告时导致应用程序崩溃

ios - 屏幕从底部移到顶部

iOS 将 CollectionView 添加到 Storyboard UI 构建器中的另一个 View