views:

243

answers:

2

Using Apple's Mail application as an example; pretend it uses Core Data. When you touch an email account, it shows you all the messages in that account. So the controller did a fetch request for all the messages in that account.

Then you touch a message and drill one level deeper, now you are viewing a single message. This single message was probably passed from the message list controller, but -- you can also click the triangles in the upper right to move through all the messages in the same email account. This means the view controller for viewing a single email message also needs the exact same list of messages.

So you could cut and paste the fetch request logic from the list view, but that isn't DRY/don't-repeat-yourself.

Any suggestions for a best practice in solving this problem?

+2  A: 

Create an object to manage your messages, then interact with that object to fetch the messages that you need for any of your view controllers. This would also allow you to switch from CoreData without changing any of your view controller logic if you decided to at a later time.

jessecurry
Thanks a lot for the suggestions Jesse. For the app I was working on, I think this would be a bit of overkill, it's a relative simple app so I want to stick to the template code as much as possible. But your solution sounds like it would be very helpful for a more complicated application.
robenk
+1  A: 

The solution I've been using to solve this problem is to use the delegate design pattern. I.e., in an application with a rootViewController and a detailViewController, the rootViewController acts as a delegate for the detailViewController.

So, for example, when the user is viewing an email message (on the detail view), and they click a button to iterate to new a message, then the detailViewController informs the rootViewController via a delegate method that the rootViewController needs to display a new message.

This way, the detailViewController only every needs to know information about one model object (the email being displayed). While the rootViewController handles interaction that involve the rest of the objects.

To me, this is a nice division of responsibility, so this is the solution I've been using.

robenk