gpt4 book ai didi

cocoa - 在 Core Data 应用程序中更新 NSTableView 的正确方法

转载 作者:行者123 更新时间:2023-12-03 16:42:20 27 4
gpt4 key购买 nike

我有一个带有 NSTableView 的核心数据项目,其中列绑定(bind)到 NSArrayController。反过来, Controller 的内容绑定(bind)到 AppDelegate 的主托管对象上下文。

我对 NSTextFieldCell 进行了子类化,以提供更自定义的数据显示方式。一切似乎都运行良好,但是当我枚举上下文中的对象并更改属性时, NSArrayController 似乎没有将新值传递到表中。我知道它们随着 sortDescriptors 的工作而发生变化,并且表格根据新数据自行组织,但同时仍然显示旧值。我猜测这归因于显示数据的 NSCell 的回收:尽管核心数据数据库中的基础值已更改,但它们并未重新绘制。

使用[myArrayController willChangeValueFor: aKeyPath]和相应的didChange以及简单的[myTable reloadData]尝试各种KVO通知后。我唯一的解决方案是取消 Controller 的 ManagedObjectContext 绑定(bind),并在处理后重新 Hook 它,如下所示:

self.hasBackgroundOp = YES;
self.isCancelled = NO; //can get changed with a 'cancel' button in the UI
if (self.managedObjectContext.hasChanges) {
[self. managedObjectContext save:nil];
}
[myArrayController setManagedObjectContext:nil]; //brutal un-hooking of controller
dispatch_group_t dispatchGroup = dispatch_group_create();
dispatch_group_async(dispatchGroup, dispatch_get_global_queue(0, 0), ^{
.
.
// create a thread context, set the persistent store co-ord
// and do some processing on the
// NSManagedObjects that are fetched into an array just
// for the purpose of this thread
.
.
[ctx save:&error];
//and after the processing is finished then refresh the table
dispatch_async(dispatch_get_main_queue(), ^{
[myArrayController setManagedObjectContext:self.managedObjectContext]; //this forces re-drawing of the table
self.hasBackgroundOp = NO;
self.isCancelled = NO;
});
});

执行[myArrayController setManagedObjectContext:nil];然后再次设置它只是为了刷新表的内容似乎真的很残酷。我简直不敢相信我已经正确地做到了这一点,尽管它工作得很好。有人可以建议更好的方法吗?谢谢!

更新:实际设置托管对象上下文并不能解决问题。它似乎已经停止工作了。如果代码连续运行两次,那么应用程序就会挂起。注释掉 -setManagedObjectContext: 行,代码可以根据需要运行任意多次。

为了响应评论,我的自定义单元格使用以下内容来显示自身:

NSInteger index = [[self stringValue] integerValue] + 1;
NSAttributedString *cellText = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%lu",index] attributes:attributes];
NSRect textRect;
textRect.origin = cellFrame.origin;
textRect.origin.x += (cellFrame.size.width - cellText.size.width) / 2;
textRect.origin.y += (cellFrame.size.height - cellText.size.height) / 2;
textRect.size.width = cellText.size.width;
textRect.size.height = cellText.size.height;
[cellText drawInRect:textRect];

数组 Controller 在主 Nib 中设置,并将其托管对象上下文绑定(bind)到AppDelegate。 nib 中没有获取请求或谓词 - AppDelegate 的代码中绑定(bind)了排序描述符:

[myArrayController setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:kINDEX ascending:YES]]];

Grab of controller options

最佳答案

我想我已经找到了它 - 我将以下内容添加到线程处理的末尾并在主线程上执行它:

[self.managedObjectContext reset];
[myArrayController fetch:self];

重置 MOC 显然会清除它,从而强制 Controller 重新绘制单元格。 -fetch 似乎是必要的,否则表格将变为空白...

关于cocoa - 在 Core Data 应用程序中更新 NSTableView 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14010187/

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