为什么NSObjectController不更新它绑定的模型属性?

时间:2016-11-20 18:13:23

标签: cocoa binding key-value-observing appkit nsobjectcontroller

我配置这样的绑定:

@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSObjectController *controller;

...

self.controller = [[NSObjectController alloc] initWithContent:nil];
[self.controller bind:NSContentObjectBinding toObject:self
          withKeyPath:@"name" options:nil];
[self.controller addObject:@"Hello"];

...

NSTextField *textField = [NSTextField textFieldWithString:nil];
[textField bind:NSValueBinding toObject:self.controller
    withKeyPath:@"content" options:nil];

文本字段在启动后显示字符串“Hello”,然后我将其更改为“World”并点击Return。但是,只更新对象控制器的内容:

[controller.content isEqualToString:@"World"]; // YES
         [self.name isEqualToString:@"World"]; // NO — WHY?
         [self.name isEqualToString:@"Hello"]; // YES

那么如何配置NSObjectController来更新它绑定的本地属性?

1 个答案:

答案 0 :(得分:0)

解决!感谢Jacob Gorban:

self.name = @"Hello";
self.controller = [[NSObjectController alloc] initWithContent:nil];
[self.controller bind:NSContentObjectBinding toObject:self
          withKeyPath:@"self" options:nil];

...

NSTextField *textField = [NSTextField textFieldWithString:nil];
[textField bind:NSValueBinding toObject:self.controller
    withKeyPath:@"selection.name" options:nil];