Pregunta

In short: I bind an NSTextField to the File's Owner (the view controller) and Model Key Path of representedObject.firstName, but editing the text field does not change the firstName.

Here are more details. I have a simple program that does nothing but create an instance of Thing (a simple class with some properties), and ThingViewController. The controller has an associated .xib with a simple UI -- a couple text fields to bind to properties of the Thing.

@interface Thing : NSObject
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic) BOOL someBool;
@end

And in the app delegate...

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    NSView *cv = self.window.contentView;
    ThingViewController *vc = [[ThingViewController alloc] 
                                 initWithNibName:@"ThingViewController" bundle:nil];
    theThing = [Thing new];
    theThing.firstName = @"Rob";
    vc.representedObject = theThing;   
    [cv addSubview:vc.view];
}

The ThingViewController.xib is simple:

enter image description here

And here is the binding for that first text field:

enter image description here

When I run, the text field does show "Rob", so it works in that direction, but then as I edit the text field, the firstName property of theThing does not change.

What am I doing wrong?

Edit: Here's a link to a zipped project file for the above code: https://drive.google.com/file/d/0B2NHW8y0ZrBwWjNzbGszaDQzQ1U/edit?usp=sharing

¿Fue útil?

Solución

Nothing is strongly referencing your view controller (ThingViewController), other than the local variable in -applicationDidFinishLaunching:. Once that goes out of scope, the view controller is released and dealloc'ed. The view itself is still around, since it is a subview of your window's contentView.

Once your view controller is released/gone, the text field has no connection back to the Thing object so it is in effect calling [nil setValue:@"New first name" forKeyPath:@"representedObject.firstName"].

Add a strong reference to your view controller (e.g., an instance variable of your app delegate) and try it again.

@implementation AppDelegate {
    Thing *theThing;
    ThingViewController *vc;
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    NSView *cv = self.window.contentView;
    vc = [[ThingViewController alloc] initWithNibName:@"ThingViewController" bundle:nil];
    theThing = [Thing new];
    theThing.firstName = @"Rob";
    vc.representedObject = theThing;

    [cv addSubview:vc.view];
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top