gpt4 book ai didi

iphone - 将 dispatch_async 与核心数据一起使用时获取 EXC_BAD_ACCESS

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

我在 coredata 中有图像,我正在尝试为表格 View 延迟加载这些图像。每个单元使用相关核心数据实体的观察者在图像可用时更新图像。实体中的相关代码如下:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// The heavy lifting seems to be during firing of the fault and accessing data,
// so i'm trying to do that in the background thread.
UIImage *i = [UIImage imageWithData:self.imageEntity.data];
// I now need to notify observers that the image is ready on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
[self willChangeValueForKey:@"image"];
image = i;
[self didChangeValueForKey:@"image"];
});
});

该项目使用 ARC,我没有收到任何编译器错误或警告,当我运行它时,它可以正常工作,直到我快速滚动,然后当我声明 i 时,我在线上收到 EXC_BAD_ACCESS。

我在这里错过了什么?

最佳答案

显然正在获取 CoreData objects is not thread safe .因此建议使用相同的 persistentStoreCoordinator,但使用不同的 ObjectContext。这是我更新后的代码,似乎不再崩溃:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
@autoreleasepool {
// Create a new context
NSManagedObjectContext *backgroundContext = [[NSManagedObjectContext alloc] init];
// Use an existing coordinator
NSPersistentStoreCoordinator *coordinator = [[DataSource sharedDataSource] persistentStoreCoordinator];
[backgroundContext setPersistentStoreCoordinator:coordinator];
// Getting objectID does not fire the fault, so we grab it but actually fetch the object
// on a background context to be thread safe.
Image *imageEntity = (Image*)[backgroundContext objectWithID:self.imageEntity.objectID];
image = [UIImage imageWithData:imageEntity.data];
// Notify observers that the image is ready on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
[self willChangeValueForKey:@"image"];
[self didChangeValueForKey:@"image"];
});
}
});

关于iphone - 将 dispatch_async 与核心数据一起使用时获取 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9408097/

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