gpt4 book ai didi

ios - 核心数据多线程——我做错了什么

转载 作者:行者123 更新时间:2023-11-29 03:16:37 25 4
gpt4 key购买 nike

我会尽量保持简短,但基本上,我有一个应用程序,在某种模式下,它可以近乎连续地记录位置和其他数据,拍摄照片(使用 AVFoundation)并将其全部存储在 Core Data 中。正如我所怀疑的那样,我发现所有这些都需要线程化……否则 UI 会变得非常缓慢。

我以前从未尝试过将 Core Data 与并发结合起来,所以我尽可能地阅读了它。我觉得我明白我应该做什么,但出于某些原因这是不对的。我因以下错误而崩溃:“非法尝试在不同上下文中的对象之间建立关系“managedDataPoint”。我知道这意味着什么,但我认为下面的内容可以避免这种情况(我正在关注我所读到的内容)。 .因为我从主上下文中获得了一个对象 ID 引用,并使用它来获取对该对象的新引用并将其传递给“临时”上下文......但这不起作用,因为核心数据仍然声称我试图建立跨上下文的关系(在哪里?)。感谢任何帮助。谢谢!

-(void)snapPhotoForPoint:(ManagedDataPoint*)point
{

if (!_imageCapturer)
{
_imageCapturer = [[ImageCapturer alloc] init];
}

if (!_tempContext) {
_tempContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
_tempContext.parentContext = self.managedObjectContext;
}

__block NSManagedObjectID* pointID = [point objectID];

[_tempContext performBlock:^{

NSError *error = nil;

Photo *newPhoto = [NSEntityDescription insertNewObjectForEntityForName:@"Photo" inManagedObjectContext:_tempContext];
UIImage *image = [_imageCapturer takePhoto];
newPhoto.photoData = UIImageJPEGRepresentation(image, 0.5);

ManagedDataPoint *tempPoint = (ManagedDataPoint*)[self.managedObjectContext objectWithID:pointID];
newPhoto.managedDataPoint = tempPoint; // *** This is where I crash

if (![_tempContext save:&error]) { // I never get here.
DLog(@"*** ERROR saving temp context: %@", error.localizedDescription);
}
}];
}

最佳答案

不应该

ManagedDataPoint *tempPoint = (ManagedDataPoint*)[self.managedObjectContext objectWithID:pointID];

不是

 ManagedDataPoint *tempPoint = (ManagedDataPoint*)[_tempContext objectWithID:pointID];

否则您将在不同的环境中工作!此外,您还应检查 objectID 是否为临时 ID 并获取“最终”ID,以防万一。

关于ios - 核心数据多线程——我做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21614176/

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