tags:

views:

226

answers:

3

I'm beginning to think that my Cocoa application is not really done according to the principles of MVC. My problem is the following:

I have some classes in my project, one of called Copier.h and another called DropReciever.h. Copier is sort of my main view controller, as it has all the bindings and main methods. DropReciever is a custom implementation of an NSView to allow the app to accept files via drag and drop.

Now, is there an easy way to send messages to Copier from DropReceiver? Right now, the two don't know each other, and I can't think of an elegant way to connect them, since since they are both kinda instantiated seperately. How can I make them see each other? Or, is there an elegant, Coca-ish way to do this better?

(If you want to look at my source code, it's here.)

+1  A: 

The way I usually do it is to instantiate DropReceiver in the nib and then add an IBOutlet DropReceiver * to your Copier.h, then drag a connection from the Copier instance to your DropReceiver in the window

cobbal
awesome. Thanks!
winsmith
I see that this was voted as the "correct" answer, but it sounds like winsmith actually wants to send messages in the other direction - from the view to the controller. This means that the view would need a `Copier *` reference, and the connection would need to be made in reverse.
erikprice
It would be fairly easy to reverse the connection, or, once the connection is made, to do some sort of delegate thing
cobbal
+2  A: 

Another way would be to expose a property of the drop receiver as a binding, and bind the copier to it (programmatically). Then, in the drop method, have the drop receiver set the dropped content as the value of this property (which you would name something like droppedObject).

When you set the property, the magic of Bindings will set the bound property of your copier. The copier can react appropriately there in its setter method.

Peter Hosey
+2  A: 

I would have a delegate property on the DropReceiver. Whatever is responsible for tying these things together would set the delegate. The delegate object can be an id, or you could create a protocol for it (both idioms are common in Cocoa). I do this all over the place. You get the separation you need, without having to work around the houses too much.

The only downside, if you don't set the delegate on initialisation, is that all your calls to it need to be protected by if( delegate ) checks.

Phil Nash
This approach is described in more detail, including handling of the responder chain, on Matt Gallagher's blog: http://cocoawithlove.com/2008/07/better-integration-for-nsviewcontroller.html
erikprice