【问题标题】:Cocoa binding programmatically + not updating value?Cocoa 以编程方式绑定 + 不更新值?
【发布时间】:2012-04-14 13:06:36
【问题描述】:

我有一个自定义类(NSView 的子类 - 实际上假设是修改后的编辑器,但不是 NSTextView 的子类),我以编程方式绑定到 NSArrayController(我绝对不能通过 Interface Builder 完成),像这样:

[myEditor bind:@"string" 
     toObject:myController 
  withKeyPath:@"selection.content" 
      options:nil];

上述方法有效,但是当值更改时,它不会更新为我的NSArrayController - 就好像它没有“粘住”一样。

我什至尝试过,使用下面的options,但无济于事:

NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys:
                         [NSNumber numberWithBool:YES],NSContinuouslyUpdatesValueBindingOption, 
                         [NSNumber numberWithBool:YES],NSAllowsEditingMultipleValuesSelectionBindingOption,
                         [NSNumber numberWithBool:YES],NSConditionallySetsEditableBindingOption,
                         [NSNumber numberWithBool:YES],NSRaisesForNotApplicableKeysBindingOption,
                         nil];

有什么想法吗?

【问题讨论】:

  • 您是如何在自定义视图中实现它的?
  • @ughoavgfhw 这是一个包含 Scintilla 组件(用于 Cocoa)的视图 - 所以,它不是定制的。它包含在 Scintilla 的正式版本中。

标签: objective-c cocoa cocoa-bindings


【解决方案1】:

一个类必须实现对绑定的支持。 Cocoa 附带的视图和单元类通常实现一组特定的绑定。自定义子类是否执行取决于实现者。

如果一个类没有实现对绑定的特定支持,那么-bind:... 请求将通过NSObject 的实现。但是,这种实施非常有限。它观察 observableController 的关键路径,并通过 KVC 更新与绑定同名的接收器的属性。但它确实不会朝另一个方向发展。也就是说,receiver 上的属性更改不会通过 key path 转发到 observableController。

使用您的示例使这不那么抽象。如果myEditor 的类没有具体实现对“字符串”绑定的支持,那么NSObject 的实现将执行[myController addObserver:<some private observer object> forKeyPath:@"selection.content" options:<...> context:<...>]

当私有观察者对象收到更改通知时,它会做[myEditor setValue:[myController valueForKeyPath:@"selection.content"] forKey:@"string"]

但是,NSObject 不会尝试观察myEditor 的“字符串”属性,也不会调用[myController setValue:<...> forKeyPath:@"selection.content"]

要详细了解如何实现对绑定的支持,请参阅Apple's documentation

【讨论】:

  • 非常感谢您的回答! :-)
猜你喜欢
  • 2012-05-23
  • 1970-01-01
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多