2

I have a newb question, which I have tried unsuccessfully to find answers for on the web. The task is simple: I want to create a core data document-based app but alter the values in some label objects. Using interface builder, I can build the core data model and populate it, using an array controller, table, etc. all without writing any code. So far so good. My test example is to build a core data model with Box entities that have length and width attributes. I would like a label to display the area, i.e. length*width for any geometrically challenged :).

So after browsing around, I've decided I need to create an NSWindowController subclass and use that to update the label when a box in the table is selected. Have attempted this, but have failed. Before I even hook up the label to the window controller, I have a problem. Following the template comments, I added this to Document.m:

- (void)makeWindowControllers
{
    NSLog(@"Adding custom Window Controller");
    MyWindowController* myWindowController = [[MyWindowController alloc] init];
    [self addWindowController:myWindowController];
}

Also added this to the template MyWindowController.m:

- (id)init
{
    self = [super initWithWindowNibName:@"MyWindowController"];
    return self;
}

The window controller has its own NIB file from Interface builder where I put the table and label etc. The file owner is set to MyWindowController. Probably forgetting other things, but that's what I remember for now.

The log message appears at startup, but then I get an exception "this class is not key value coding-compliant for the key managedObjectContext" before the window appears. I'm guessing that I don't have the window controller hooked up to the document class properly? My other thought is that the array controller is in the window controller nib, not the document nib, so maybe it's looking in the wrong place for the managedObjectContext?

4

1 回答 1

0

我会尝试另一种方法:作为只读属性添加area到您的实体中。Box使用 Xcode自动创建一个Box类(查看数据模型时“编辑器”菜单中的“创建 NSManagedObject 子类”菜单项),然后将其添加到 Box.h

@property (weak, readonly) NSString * area;

这给 Box.m

- (NSNumber *)area
{
    return [NSNumber numberWithDouble:([[self length] doubleValue] - [[self width] doubleValue])];
}

+ (NSSet *)keyPathsForValuesAffectingArea
{
    return [NSSet setWithObjects:@"length", @"width", nil];
}

如果这样做,您可以像绑定其他属性一样绑定area到标签值。Box无需子类NSWindowController化或观察变化。

于 2015-03-19T16:46:06.730 回答