iOS MVC Pattern – Proper Implementation Guide

design-patternsiosmvcobject-orientedobjective c

After browsing the apple docs, I came across this sample of their MVC pattern:

mvc

Using NSNotificationCenter and without using KVO, would this diagram below represent a correct implementation of the MVC pattern? If not, what’s wrong and how can it be corrected or improved?

mvc example

  1. App starts with the left light set to on, and the right one off. Only one light may be on at a time.
  2. Users presses the right switch, which sends a target action to the view controller.
  3. The view controller receives the message, and send a message to the right light data model.
  4. The right light uses NSNotificationCenter to notify the controller the right light has changed.
  5. The controller receives the message, and performs the following method

    BOOL rightLightOn = [rightLightData on];
    if( rightLightOn )
    {
    [rightLightImage setImage:onImage];
    [leftLightSwitch setOn:NO];
    }
    else
    {
    [rightLightImage setImage:offImage];
    }

  6. The switch change causes the UISwitch to call the method “leftSwitchChanged” in the controller.

  7. The controller receives the message, and send a message to the left light data model.
  8. The left light uses NSNotificationCenter to notify the controller the left light has changed.
  9. The controller receives the message, and again performs the same method shown above, but modified for the right light.

In addition, what if the system wasn’t using a switch, and instead was using a UIButton that displayed the text, “Turn On” or “Turn Off.” Would the switch update it’s own text, then call “rightSwitchChanged” or would it call rightSwitchChanged immediately and wait for the view controller to change the text?

Best Answer

Yes it fits the pattern. But...

I'm not a fan of notifications in iOS. In fact in many cases they are used as glorified gotos.

If you call [model setLightOn] why would the model need to send you a notification back that the light is on? It's on!

One other nit-picky comment: setLightOn is a poor name. setLightOn:NO - does this turn the light off or just ignore the message?

Related Topic