Re: Setting Up a MVC most of it works BUT
Re: Setting Up a MVC most of it works BUT
- Subject: Re: Setting Up a MVC most of it works BUT
- From: Jens Alfke <email@hidden>
- Date: Fri, 10 May 2013 11:57:00 -0700
On May 9, 2013, at 6:57 PM, Graham Cox <email@hidden> wrote:
> a) the data model explicitly calls a method of the controller to tell it about a change. This isn't great, because it sets up a strong dependency between the data model classes and the controller class(es).
> a+) the data model declares an informal or formal protocol that some designated object (called a delegate, and this could be your controller) can implement. The data model calls these delegate methods for certain specific activities. This is really just a more elaborate form of a), which is why I call it a+, though with care it can be more generic and anonymous, and therefore can have better decoupling than a.
Delegation is the tool I reach for most often for this type of communication. It avoids tight dependencies because the model doesn’t know about the controller, it just specifies what messages its delegate should understand. I find this style conveys a lot of information to someone reading the code, because it formalizes the “outgoing” API of the model class, and also makes it very clear what the parameters and their types are.
This pattern is used all over Cocoa, especially in UIKit and AppKit, so there are tons of examples in the system headers. (For example, look at NSURLConnectionDelegate.) One gotcha to be aware of is that the reference from the model object to its delegate should be weak, i.e. unretained, to avoid setting up reference cycles.
The drawback is that it’s a to-one relationship: a model object can have only one delegate, unless you put some work into supporting a collection of them. Generally, once you have a need for multiple observers to know about changes to one object, you reach for the NSNotification or KVO hammers instead.
—Jens
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden