【问题标题】:Why is NSViewController not binding representedObject?为什么 NSViewController 不绑定代表对象?
【发布时间】:2014-03-22 03:44:27
【问题描述】:

简而言之:我将NSTextField 绑定到文件所有者(视图控制器)和representedObject.firstName 的模型键路径,但编辑文本字段不会更改firstName

这里有更多细节。我有一个简单的程序,除了创建Thing(具有一些属性的简单类)和ThingViewController 的实例之外什么也不做。控制器有一个关联的.xib 和一个简单的用户界面——几个文本字段绑定到Thing 的属性。

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

在应用委托中...

- (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];
}

ThingViewController.xib 很简单:

这是第一个文本字段的绑定:

当我运行时,文本字段确实显示“Rob”,因此它朝那个方向工作,但是当我编辑文本字段时,theThingfirstName 属性没有改变。

我做错了什么?

编辑:这是上述代码的压缩项目文件的链接:https://drive.google.com/file/d/0B2NHW8y0ZrBwWjNzbGszaDQzQ1U/edit?usp=sharing

【问题讨论】:

  • 试试“不断更新价值?”在带有令牌字段的核心数据上下文中对我来说是必要的。用户的编辑不会立即推送到模型。
  • 我试过了,但没有看到行为改变。

标签: cocoa osx-mavericks cocoa-bindings nsviewcontroller


【解决方案1】:

除了 -applicationDidFinishLaunching: 中的局部变量外,没有任何东西强烈引用您的视图控制器 (ThingViewController)。一旦超出范围,视图控制器就会被释放并释放。视图本身仍然存在,因为它是窗口 contentView 的子视图。

一旦您的视图控制器被释放/消失,文本字段就没有与 Thing 对象的连接,因此它实际上是在调用 [nil setValue:@"New first name" forKeyPath:@"representedObject.firstName"]。

添加对您的视图控制器的强引用(例如,您的应用委托的实例变量)并重试。

@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];
}

【讨论】:

  • 做到了。我还没有从 JVM 和垃圾收集世界重新训练。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
  • 2018-05-18
  • 2022-01-11
相关资源
最近更新 更多