objective-c - 如何使用核心数据设置 NSArrayController?

标签 objective-c macos core-data nsarraycontroller

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

我知道我的核心数据存储有内容,因为我可以通过托管对象上下文手动检索对象。我将 NSArrayController 连接到相同的托管对象上下文,然后将 NSTableColumn 的值参数绑定(bind)到 NSArrayController

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

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

界面

@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: 不等待数据加载,而是立即返回。

这在支持绑定(bind)的环境中是有意义的。您通常有一个绑定(bind)到数组 Controller 的 TableView ,它会在 Controller 内容更改时更新。

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

[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

关于objective-c - 如何使用核心数据设置 NSArrayController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8229248/

相关文章:

iphone - block 返回错误

iphone - 表示警报一天中时间的正确方法

macos - 在 Linux 中使用大中央调度

objective-c - 旋转 NSButton 不起作用

objective-c - osx - touchesBegan 没有结束也没有取消

ios - 父 MOC 从子 MOC 获取空数据的变化

ios - 根据请求的参数映射资源

ios - 如何从 iOS 字典中给定的值中查找键

swift - 在核心数据实体中使用枚举类型值

iphone - 记录的url保存在核心数据中,但我稍后尝试使用它时不起作用