如何使用核心数据设置

如何使用核心数据设置

本文介绍了如何使用核心数据设置 NSArrayController?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式设置一个 NSArrayController 以使用 Core Data.

I am trying to programmatically setup an NSArrayController to work with Core Data.

我知道我的 Core Data 存储有内容,因为我可以通过托管对象上下文手动检索对象.我将 NSArrayController 连接到相同的托管对象上下文,然后将 NSTableColumn 的 value 参数绑定到 NSArrayController.

I know that my Core Data store has content since I can manually retrieve objects through the managed object context. I hooked up an NSArrayController to the same managed object context and then bound the value parameter of a NSTableColumn to the NSArrayController.

我要求 NSArrayController 去获取,但它返回一个空数组.

I asked the NSArrayController to fetch but it returns an empty array.

对我可能做错了什么有什么建议吗?

Any suggestions on what I might be doing wrong?

界面

@interface MTTableViewController : NSObject <NSTableViewDelegate, NSTableViewDataSource>
{
    NSMutableArray *tableData;
    MTTableCell *tableCell;

    IBOutlet NSTableColumn *tableColumn;
    NSArrayController *dataController;
}

实施

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self)
    {
        dataController = [[NSArrayController alloc] init];
        [dataController setManagedObjectContext:[[NSApp delegate] managedObjectContext]];
        [dataController setEntityName:@"Track"];
        [dataController setAutomaticallyPreparesContent:YES];

        [dataController fetch:self];
        NSArray *content = [dataController arrangedObjects];
        NSLog(@"Count :%i", (int)[content count]); //Outputs 0

        tableCell = [[MTTableCell alloc] initTextCell:@""];
        [tableColumn setDataCell:tableCell];
    }

    return self;
}

推荐答案

fetch: 不会等待数据加载,而是立即返回.

The fetch: doesn't wait for data to be loaded, instead it returns instantly.

这在启用绑定的环境中是有意义的.你通常有一个绑定到数组控制器的表视图,它会在控制器内容改变时更新.

This makes sense in bindings-enabled environment. You usually have a table view bound to an array controller, which updates whenever controller content changes.

在这种情况下,您可以观察控制器 arrangedObjects 的变化:

In this case you could observe for changes in arrangedObjects of the controller:

[self.arrayController addObserver:self forKeyPath:@"arrangedObjects" options:NSKeyValueObservingOptionNew context:NULL];

然后:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  NSLog(@"Data: %@", self.arrayController.arrangedObjects);
}

来源:https://stackoverflow.com/a/13389460

这篇关于如何使用核心数据设置 NSArrayController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 12:47