0

I'm having trouble figuring out the right way to bind an NSArrayController (in turn bound to by a table view) to an NSArray property of an NSDocument instance via a view controller.

My NSDocument subclass has a property NSArray * pages. I first mirrored the pages property in the view controller, but that means that the table view does not update when the NSDocument adds items to its pages array. The only ways to force an update in this case are either will../didChangeValueForKey:@"pages" in the view controller, but that's not practical when the change is not triggered from the view controller. Calling will/didChangeValueForKey in the NSDocument directly does not trigger the array controller to update.

I tried to bind directly to the ViewController's document.pages, but that doesn't seem to work, or at least doesn't show any updates, either.

What would be the right technique to use here?

fbitterlich
  • 882
  • 7
  • 24
  • Did you check if the `pages` property follows the rules of [KVO Compliance](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/KeyValueObserving/Articles/KVOCompliance.html#//apple_ref/doc/uid/20002178-BAJEAIEE)? – Willeke Apr 26 '17 at 16:13
  • Since NSDocument is inheriting from NSObject, I assume it is KVO compliant. The pages property is deffined as `@property (nonatomic, strong) NSMutableArray *pages;` - from what I understand, that should be all that is required, right? – fbitterlich Apr 26 '17 at 16:22
  • If you do `self.pages = someArray` yes, if you do `[self.pages addObject:someObject]` no. You have to use `mutableArrayValueForKey:` or `willChange:valuesAtIndexes:forKey:`/`didChange:valuesAtIndexes:forKey:`. – Willeke Apr 27 '17 at 00:30

1 Answers1

0

Solved - even though the problem was not where I was looking for it.

I was binding the Array Controller to a document property created like this:

- (Document *)document {
    return (Document *)self.view.window.windowController.document;
}

That does not work, because it is not KVO-compatible. The solution was to simply assign the NSDocument instance to self.representedObject, which is a "real" property and thus observable.

Wrapping changes to the pages array into willChangeValudForKey: / didChangeValueForKey: does work to update the bound Array Controller as expected, although the more specific versions Willeke suggested in his comment are probably more correct.

fbitterlich
  • 882
  • 7
  • 24