2011-02-15 39 views
1

经过几个小时/天的搜索和潜水示例项目,我已经断定我需要问一下。如果我将assetsView(IKImageBrowserView)直接绑定到NSArrayController的IB实例,则一切正常。如何以编程方式用CoreData行填充NSArrayController?

- (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都是空的。我知道我错过了一些东西......我只是不知道是什么。目标是最终允许用谓词以编程方式过滤此视图的“库”的多个实例。现在我只是想让它显示“资产”实体的所有行。

此外:如果我在IB中创建NSArrayController,然后尝试记录[library arrangedObjects]或手动设置assetsView的数据源,我会得到相同的空结果。就像我之前说过的,如果我在IB中绑定library.arrangedObjectsassetsView.contentIKImageBrowserView) - 具有相同的托管对象上下文和由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]; 
} 

回答

0

它看起来像问题是你实际上没有告诉NSArrayController来获取任何东西。除非通过绑定或手动添加对象,否则NSArrayControllers为空。

设置库后尝试调用它的获取方法:

[library fetch:self]; 

而且,你可能已经知道了,但它可以在代码中设置绑定使用下面的方法:

- (void)bind:(NSString *)binding toObject:(id)observableController withKeyPath:(NSString *)keyPath options:(NSDictionary *)options 
9

即使ArrayController最终会与NSManagedObjectContext同步,我也遇到了(IKImageBrowserView)未初始化的类似情况。

最终发现在核心数据节目指南此通道

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdBindings.html#//apple_ref/doc/uid/TP40004194-SW3

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]; 
// ... 
0

也可以用在awakeFromNib如果创建子类NSArrayCotroller或添加通过您的视图控制器

-(void)awakeFromNib 
{ 
    [self fetchWithRequest:nil merge:NO error:nil]; 

    ... 
} 
相关问题