简体   繁体   中英

What's the standard way for NSDocument to send events to NSViewControllers?

(Background: I've got a Cocoa app I'm writing that works fine, but is too complex because it doesn't have good separation of model/view/controller. Therefore, I'm updating it to use NSDocument and NSWindowController/NSViewController. On the whole, this is a good change, but there are a few parts that I don't quite understand yet.)

I've got an NSDocument that holds the document state, and a hierarchy of NSWindowController -> NSViewControllers that manage the logic. When a view controller responds to user input and needs to change some state, it can easily get its NSDocument and call a method on it to make the requested change (which will also register it with the undoManager, and so on). That direction works fine.

But the other direction is less clear. When the NSDocument makes a change (perhaps in direct response to a user edit, but perhaps not), how does it typically send the event down to the view controllers to update the views?

I see some handy diagrams here in Apple's documentation but it's not clear to me what they're trying to show. An orange arrow is defined as "Owns and manages", but it never says what a dotted arrow, a double-ended arrow, or a double-headed arrow means.

Do they mean to suggest that applications typically have every type of state-change represented by methods in their NSWindowController, which passes them to corresponding methods down the NSViewController tree? This seems rather clumsy.

Right now, I'm leaning towards having my NSDocument post NSNotifications for all changes, and then let NSViewControllers register for exactly the notifications they care about. This seems less clumsy, but perhaps still not ideal.

EDIT: Or KVO? Apple's example does use KVO a little bit, but it also has a much simpler data model. I'm not sure that'll work for me, and it also seems like something that is not entirely in line with where Swift is headed. I don't want to jump on something that doesn't have a good future.

Everything I've read says to avoid KVO, and that KVO has the worst API in all of Cocoa. So let's just skip that.

This old post on com.sys.mac.programmer.help says that NotificationCenter is a fine solution:

my preference has been to post a notification in my setters in the model and register my window controllers (or whatever controller is controlling the views) to receive those notifications

It's surprisingly difficult to find sample programs which use NSDocument, for some reason, but here's a simple example of a program that uses this pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM