Using iPhone NSNotifications in MVC app
I have an NavigationController based app where the data model is stored in the appDelegate after being fetched using开发者_开发问答 CoreData. The views that display the data all have a pointer to appDelegate so that they can query the model for the required data. They then call methods in the appDelegate in response to user selections.
My question is, doesn't the MVC pattern optimally hide the data from the view? Would it be best practice for the appDelegate (in this case serving as model and controller) to supply the data to the view, and for the view to simply send a notification when there is user input? That would eliminate the need for the view to maintain a pointer to the appDelegate.
You're correct to worry about AppDelegate taking on this role. AppDelegate is an easy place to dump stuff, and it quickly becomes overwhelmed with roles. As you note, it's playing data model, data controller and application delegate. If you're getting to the AppDelegate using [[[UIApplication sharedApplication] delegate]
, it's especially a problem because it makes it very hard to reuse the view in other programs. It's less of a problem if your view has a delegate
ivar that just happens to point to the AppDelegate, but could easily point to some other object.
The view often should have a delegate that it passes UI events to. See UITextField
and UITextFieldDelegate
for a good example pattern. Views generally don't post NSNotification
for this kind of stuff. Conversely, model classes typically work best without delegates in my experience.
I am a huge believer in NSNotification
. My programs use them for almost all data that moves up from the model layer. But for actions that move down from the view layer, delegation and direct method calls typically work best.
Its not your view that accesses the data. The controller should be the link between the data and the view. If by view you mean the controller, then that's perfectly fine and basically what MVC is all about.
精彩评论