gpt4 book ai didi

ios - 在不同线程上访问 NSManagedObject 的 objectID?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:22:46 28 4
gpt4 key购买 nike

我的 UITableViewCell 的部分内容创建因一个对象 (CoreData NSManagedObject) 初始访问时发生的故障而延迟。这表现为一个小问题,单元格首先滚动到 View 中。我决定将对这些对象的访问推送到后台线程。

我就是这样实现的,效果很好,但是我们都知道我们不应该在另一个线程中访问一个线程(主线程)的 NSManagedObjectContext,但是我们可以在一个线程中获取对象的 objectID如果它最初是在第一个线程中获取的,第二个线程?

获取 objectID 需要花费少量时间,我希望将其与其他所有内容一起插入后台。

MyRecord *record = [self.frc objectAtIndexPath: indexPath];

// Should the following be here or can it be below in the background thread?
// NSManagedObjectID *recordObjectID = record.objectID;

dispatch_async(_recordViewQueue, ^(void) {
if ([cell.origIndexPath isEqual:indexPath]) {

// should the following be here or above? It works here, but am I just lucky?
// this call seems to take about 2/100 of a second
NSManagedObjectID *recordObjectID = record.objectID;

NSManagedObjectContext *bgndContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];
bgndContext.persistentStoreCoordinator = App.sharedApp.storeCoordinator;
MyRecord *newRecord = (MyRecord *) [bgndContext objectWithID:recordObjectID];

[self updateCell:cell withRecord:newRecord];

if ([cell.origIndexPath isEqual:indexPath]) {
dispatch_async(dispatch_get_main_queue(), ^{
[(UIView*) cell.recordView setNeedsDisplay];
});
}
}
});

这样安全吗?还是我必须在 mainThread 中获取 objectID?

最佳答案

在线程之间传递托管对象的 objectID 是安全的。在线程之间使用托管对象是不安全的。使用 objectID 和线程的托管对象上下文调用 existingObjectWithID:error: 以获取该线程的托管对象的实例。

我会像这样更新您的代码:

MyRecord *record = [self.frc objectAtIndexPath: indexPath];

NSManagedObjectID *recordObjectID = record.objectID;

dispatch_async(_recordViewQueue, ^(void) {
if ([cell.origIndexPath isEqual:indexPath]) {

NSManagedObjectContext *bgndContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];
bgndContext.persistentStoreCoordinator = App.sharedApp.storeCoordinator;
NSError * error = nil;
MyRecord *newRecord = (MyRecord *) [bgndContext existingObjectWithID:recordObjectID error:&error];
if (newRecord) {
[self updateCell:cell withRecord:newRecord];
if ([cell.origIndexPath isEqual:indexPath]) {
dispatch_async(dispatch_get_main_queue(), ^{
[(UIView*) cell.recordView setNeedsDisplay];
});
}
}
else {
NSLog(@"unable to find existing object! error: %@ (userInfo: %@)", [error localizedDescription], [error userInfo]);
}
}
});

关于ios - 在不同线程上访问 NSManagedObject 的 objectID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17958381/

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