经过几个小时/几天的搜索和深入研究示例项目后,我得出的结论是我需要问一下。如果我将 assetView (IKImageBrowserView
) 直接绑定(bind)到 NSArrayController
的 IB 实例,一切都会正常工作。
- (void) awakeFromNib
{
library = [[NSArrayController alloc] init];
[library setManagedObjectContext:[[NSApp delegate] managedObjectContext]];
[library setEntityName:@"Asset"];
NSLog(@"%@", [library arrangedObjects]);
NSLog(@"%@", [library content]);
[assetsView setDataSource:library];
[assetsView reloadData];
}
两个 NSLogs
都是空的。我知道我错过了一些东西......我只是不知道是什么。目标是最终允许使用谓词以编程方式过滤此 View “库”的多个实例。现在我只是想让它显示“ Assets ”实体的所有行。
补充:如果我在IB中创建NSArrayController
,然后尝试记录[libraryarrangedObjects]
或手动设置assetsView的数据源,我会得到相同的空结果。就像我之前所说的,如果我将library.arrangedObjects绑定(bind)到IB中的assetsView.content(IKImageBrowserView
) - 具有相同的托管对象上下文和相同的实体由 IB 设置的名称 - 一切都按预期进行。
- (void) awakeFromNib
{
// library = [[NSArrayController alloc] init];
// [library setManagedObjectContext:[[NSApp delegate] managedObjectContext]];
// [library setEntityName:@"Asset"];
NSLog(@"%@", [library arrangedObjects]);
NSLog(@"%@", [library content]);
[assetsView setDataSource:library];
[assetsView reloadData];
}
最佳答案
我遇到了类似的情况,即使 ArrayController 最终与 NSManagedObjectContext 同步,(IKImageBrowserView)也没有初始化。
最终在核心数据编程指南中找到了这段话
if the "automatically prepares content" flag (see, for example, setAutomaticallyPreparesContent:) is set for a controller, the controller's initial content is fetched from its managed object context using the controller's current fetch predicate. It is important to note that the controller's fetch is executed as a delayed operation performed after its managed object context is set (by nib loading)—this therefore happens after awakeFromNib and windowControllerDidLoadNib:. This can create a problem if you want to perform an operation with the contents of an object controller in either of these methods, since the controller's content is nil. You can work around this by executing the fetch "manually" with fetchWithRequest:merge:error:.
- (void)windowControllerDidLoadNib:(NSWindowController *) windowController
{
[super windowControllerDidLoadNib:windowController];
NSError *error = nil;
BOOL ok = [arrayController fetchWithRequest:nil merge:NO error:&error];
// ...
关于objective-c - 如何以编程方式用 CoreData 行填充 NSArrayController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5002258/