gpt4 book ai didi

objective-c - 后台线程和主线程同时访问核心数据时应用程序崩溃

转载 作者:行者123 更新时间:2023-12-01 17:33:56 24 4
gpt4 key购买 nike

我的情况是我的应用程序使用核心数据,并且需要从该核心数据加载图像以显示在表格 View 中。由于这样做需要时间,它需要在后台线程中运行。所以我有这样的代码:

dispatch_async(queue, ^{

if (self.cellInfo.numberOfMediaItems > 0) {

int i = 0;

int numberOfThumbnails = MIN(self.cellInfo.numberOfMediaItems, 3);

while (i < numberOfThumbnails) {
Media *media = [self.entry.media objectAtIndex:i];

UIImage *image = [media getThumbnail];
[self.mediaArray addObject:image];
i++;
}
}

dispatch_async(dispatch_get_main_queue(), ^{
self.isFinishedProcessing = YES;

[self setNeedsDisplay];
});

});

这大大加快了该过程,并且图像在准备就绪时出现在背景中。

问题是,有时它会让前台线程与后台线程同时尝试访问核心数据。它不喜欢这样,所以它崩溃了。这一定是很多开发人员都会遇到的情况,因此有一个解决方案。我想知道如何处理这种情况,以便我的应用程序在它们同时开始访问核心数据时停止崩溃?

最佳答案

See my previous answer here .

There is a golden rule when it comes to Core Data - one Managed Object Context per thread. Managed object contexts are not thread safe so if you are doing work in a background task you either use the main thread to avoid threading conflicts with UI operations, or you create a new context to do the work in. If the work is going to take a few seconds then you should do the latter to stop your UI from locking up.



简而言之,您需要创建一个单独的托管对象上下文以在后台线程中使用。然后,您必须在适当的地方将更改合并回原始上下文。

关于objective-c - 后台线程和主线程同时访问核心数据时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10819217/

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