Skip to content

Archive

Tag: MVC

Starting with a naive MVC application my goal was to provide automated testing over headless graphics (e.g. using a standard test suite). How can we modify an application so that it can be used either by a real world user or by a robot?

I started with a concept (‘the user agent’). This is somewhat useful and helped clarify the application structure. However, it seems a better way to get this to work is may be to just write a couple of tests ‘assuming the underlying system’ is already compatible with our new requirements – in other words, design the solution outside-in.

Additionally, I’m looking into existing automations for iOS; I will shortly review a couple of attractive solutions.

The user agent

A so called user agent (I may be abusing the term) is an interface bridging the view and the controller. Why would it be useful to complicate our design in this way?

Initially, an MVC application works like this:

USER <=> {View} <=> {Controller} <=> { Model } (2)

With a testing automation, it may look like this:

{ Robot } <=> {View} <=> {Controller} <=> { Model }

Indeed certain automations work this way (great); what about testing over headless graphics?

  • The view component must not be instantiated.
  • We cannot instantiate the controller unless we hide/factor out view dependencies.

We could write tests that only exercise the model; not bad, maybe too far removed from our goal.

So the idea is to introduce an interface (‘user agent’) bridging the view and controller; then we could setup the application in either of two ways:

USER <=> View <=> { UA } <=> {Controller} <=> { Model }

{ Robot } <=> { UA } <=> {Controller} <=> { Model }

A quick refactoring

Clearly dependencies between the view and controller need to be factored out in order to realize the above. Initially the controller owns a reference to the view and may processes UI events.

One way to proceed:

  1. Migrate event handling code to the UI; inside event handling code we invoke controller methods.
  2. Provide interfaces (e.g. IUser or IUserInput, IUserOutput) that the controller uses to output to, or configure input from, the UI. The UI implements these interfaces.
Then the situation is like this:
View (Event Handlers) => Controller
Controller => View <IUser>
I have done exactly that with our application code. This refactoring is not overly time consuming.
Formally, the approach does not seem incorrect. We can write a Robot class implementing <IUser> and Robot can directly invoke controller methods. This approach, however, should be validated by answering the following questions:
Can we easily write acceptance tests?
Can we generate tests by recording sessions?
Session recording/playback
It appears that recording messages issued by the UI may not be very easy with the above solution. The idea is simple. In practice, however, the controller is often defined as an aggregation (a hierarchy of controllers):
  • RootController
    • ControllerA
    • ControllerB
Now, we can pass a Recorder to all controllers down the hierarchy and certain methods in each controller would generate messages sent to the recorder. Having to record from (and playback to) a graph instead of a single object is a complication that should be avoided. Further (contingent to the above refactoring) it is not clear which invocations should be recorded (cf. “certain methods”).
In short, it would be reasonable to introduce an interface that captures messages from the view to the controller:
View (Event Handlers) => Controller <IApplication>
Controller => View <IUser>
Writing acceptance tests
For the programmer writing acceptance tests, the controller hierarchy appears untidy. Although controller classes look ‘higher level’ once event handling code has been factored out, the methods are still designed to be called by the UI in response to user events. This may involve continuous input as well as fairly idiosyncratic sequences. As a result, introducing <IApplication> as suggested above may not be sufficient. Compared to interaction records, manually written tests should be fairly ‘stylized’.
One solution may be to write a Robot class used to capture requirements for writing acceptance tests.
Where is the UA?
A quick refactoring is insufficient. We need more kit to get this to work. The UA would then be realized by several interfaces:
  • <IUser> specifies methods invoked by the controller in order to display output or configure user input
  • <IApplication> specifies methods normally invoked by the UI in order to operate the application. Invocations of IApplication may be recorded for later playback.
  • A Robot class may define high level methods used to manually write tests.

To be continued…

My impression at this point is that I may have jumped in too quickly – starting to design based on a ‘good idea’ instead of formalizing use cases.

The UA idea is ‘kind of good’. But it took time to move from the idea to an understanding of what the UA might actually be.

Actually, the most productive step was not thinking about the UI but defining a new initializer for the session, like thus:

Session initWithContext:(id<SessionContext>)context

Where:

  1. Session represents a user session; roughly matches the model/controller.
  2. SessionContext is intended to capture anything that a user session may require to boot and run, with or without headless graphics.
    • A live session context would provide a UI.
    • A testing context would not provide a UI.
  3. Session can be instantiated in a headless graphics environment.

If a session can be defined in this way, we have done half of the work.

(tbc)

Here’s an idea that may work for some of us. I’ll try this next week if, and only if, I run into annoyances:

Let’s take an example:

  1. We have a Model class. The model class is just a placeholder for data.
  2. We have a Request class. The request class is just querying a server for data.
  3. We have a controller that (a) fires the Request and receives its response and (2) passes the result to the model.

Does the controller need to effect this operation? Think not. Maybe the controller shouldn’t control this.

The business logic argument

The described operation is exposing too much of the model in the wrong way. The controller should care about how the model updates only insofar as the view may need to render something about it.

If we need the view to let the user know that a request has been sent, what we’re really asking for is the model to fire an event to let us know, and the controller to handle this event.

The clarity argument.

Controllers easily get intricate. If we can move something from the controller to the view or the model, we should.

I like to have struct like classes that not define any operations. This isn’t incompatible. More often than not, model operations can be neatly defined using commands. Otherwise, we can fall back on a model/data split, where the model is a kind of ‘data controller’ viz. the model holds no state, only business flow, and the data holds no function, just data.

The integration argument

If the controller is manipulating view and model states too finely, service integration is reduced. Instead of having qualified, usable views and models, we have particulate, D.I.Y views and models that turn out, more often than not, to provide the kind of flexibility attracting bugs and reducing maintainability.

A particular, enlightening scenario is when the model or view expose sufficient state that they could not avoid being put into an inconsistent state by a careless controller. Hey, we got a nice little rule here:

If a view or model’s interface allows putting such view or model in an inconsistent state, there is too much logic in the controller.

An organic, yet ideal controller

An ideal controller should…

  1. Hold no state
  2. Receive events from the view and model
  3. Issue high level commands mapping the model to the view, and vice versa.
  4. Be thin.
  5. Look boring and redundant.

Why (5)? well, that’s good, and that’s why we often wonder what the controller is for. Here’s an example:

  1. Play button is pressed and fires an event
  2. Controller handles the event and invokes the model’s play method.

That’s boring, yet performs an awfully simple function: decouple the view from the model. Because it is boring and simple, it also makes a fair allowance for ‘becoming more complicated later on’ without anticipating over much anything at all. This isn’t planning what features we’ll need in six months, it’s just a kind of placeholder for future intricacies.

On the other hand, here’s a counter-example

  1. Play button is pressed and fires an event
  2. Controller handles the event
  3. Controller creates a download stream.
  4. Controller receives a callback to indicate the stream is connected (and sets a ‘control state’ flag)
  5. Controller  changes the color of the play button.

The good news

Interaction can easily get complex. Models and views can also get complex. Let the controller be thin and stateless. If our controllers are more concerned with the semantics of interaction, and less with rendering and model updates, they are better controllers.

The bad news is, it’s easy to push too much logic in a controller. The good news is, it’s easy to take it out.

I wrote a little, here and there, about the so called F* meta-pattern. I created F* to close a bag of worms. However… …F* is merely a minority report. A kind of footnote to MVC.

In the grand scheme of corporate front end development, MVC stands out for super-structure. To begin with, it doesn’t take a genius architect to work out labour separation. We named Max, Vincent and Connie. How many Frogs would it take to maintain an F* app?

Incidentally, the bag of worm re-opened when I tried to explain the command pattern to a new recruit, and got a poor old MVC natural on my doorstep the next day.

What would you do? Rewrite the whole thing? I didn’t. I tried fixing it up. Now’s a time for rambling and recriminating.

Post-scriptum

OK then. This post is about MVC the way people do it ‘their own way’. Without using frameworks, and without using the command pattern. This post doesn’t contain answers. It’s just listing lazily a lot of scary/worrying/time consuming issues.

Command patterns and frameworks have one thing in common. They’re a little heavy. Heavy can mean a lack of concision and elegance. It can also imply conceptual overhead. Heavy can also cover an element of cultural difference. Either way…

…heavy isn’t for everybody. I didn’t write heavy code when I was 17. I did write some cool stuff though, including stuff I would only half-guttedly replicate today. So this post is raising an issue: can we still just write a little bit of code, and get away with it?

Finally, before you read away, be assured this isn’t a spoiler. If you want to do your own MVC stuff without a command pattern and without a framework, it won’t protect you against unpleasant surprises.

May refactoring be with you.

It all started with a view, a model and a controller…

Back when I started ‘doing MVC’…

  1. Write a *Model* class containing a few bites (no bits, no bytes) of data.
  2. Write a *View* class batching a couple of widgets.
  3. Write a *Controller*. The controller instantiates and refers the *View* and the *Model*.
  4. Let the controller listen to events from the view and the model.
  5. In response to view/model events, let the controller update the view and modify the model.

Really doing it

If you really are doing MVC the wild way  (or maybe just writing a moderately sizable app) then you’ll need to go a little further:

  • Writing components. For lack of a better word, I refer to ‘mini-apps’ – bunches of MVC classes that work together to realize a feature in a larger app – as ‘components’. Components needn’t be hard to write, and in theory the ‘scaling up’ question needn’t interact with whatever well-formed approach to MVC we’re using (why? because either way the secret is to keep components decoupled. A ‘keep the bags of crap small enough’ idea that I’ve been pushing forward in my posts about F*).
  • Writing ‘models’. I hope you’re not trying to get your way around TableModel, ListModel and other API induced models, and how they should fit in our MVC collection. Because I am, and I wish to be enlightened.
  • Keeping it small and simple. We don’t want our apps to grow any bigger or more complex than they ought to be. Or do we? Unfortunately trying to keep front ends manageably small is a good way to make them unbearably intricate. At the other end of the scale, fixing the same bugs in countless apps ‘prototyped one another’ resurrects Taylorism.

Before things go wrong

Before things get really nasty, here are the tell-tal signs that might finally help us understand what to do with our MVC naturals.

Getting confused and arguing over it

When I started with my 3D engine, I considered that 3D assets were view. Unfortunately, 3D geometry affects game logic. Sometimes also, 3D assets are adequately used to hold data that (I think) ought belong to the model. Some guys quickly judge this kind of situation and get over it. Your colleagues from the front end get into heated discussions about what goes in the M or V or C. You think it’s a waste of time and you’re perfectly right. If there’s no hard business/real world constraint driving towards a correct answer, it’s like naming a baby can get. Oh my.

What is the controller?

I felt immensely relieved when I heard a colleague say this for the first time. Here’s why. Because every so often, the view is specifically written for the model. Most of us understand why you would want to change/write a different view for the same model. Many of us acknowledge that views are disposable app-fodder. Views are ad-hoc. In short, the view root can listen to widget events and effect model changes directly. So why do we need a controller?

Why we cannot write clean components.

Because the UI is bullshit, or the UI is bullshit.

If you give the UI work to a UI designer, they’ll think about usability. They’ll make a UI that has weird shortcuts. The component hierarchy won’t match the model’s functional hierarchy. In short, the UI won’t map your model closely. If it’s a good UI, it will even get literally (legitimately) intricate. Meaning that the hierarchy will be unclear enough that you won’t be able to ‘just take a component and drop it into another app’. Business apps should be more tractable. That’s because…

Usability is irrational bullshit. Unfortunately business apps also are bullshit. They are boring, slow to use and un-fun. That’s why people are paid to use them.

What are view states?

We’re writing an app allowing people to choose shirts. Shirts come in different colors. The UI designer suggests that the ‘add’ buttons in the shopping cart should match the shirt colors. What’s going on?

This is just a silly (and actually, redemptory – the ‘color state’ is blissfully captured by the natural data model) version of the model-view/view-model dilemma. View has states that aren’t perceived to partake the model. However such states can be linked to the model, and more often than not, these states also persist in real apps (as in, real-world apps persist their UI states). Here are three perspectives on the situation:

  1. If it’s a variable, it’s a state. State belongs to the model. My first tech lead frustrated me a little by implying this is obvious. Is it obviously right to conflate the data, or (as he suggested) whatever is the data model (4th tier alarm!) with cosmetic stuff like font size, colors and alignments?
  2. Add view.model, view.controller, view.view to your view package. Call a cat a cat. While this may seem logical, it needn’t take us very far. If we’re not serious about our view, that’s OK. Otherwise we’re reducing separability in unpredictable ways. Most apps do MVC just to keep things neat and clean. If separability has business strings attached, there will be a price.
  3. Don’t confuse data and model. More specifically, don’t confuse the view model and the data model. That’s a weird avatar of (1) and I don’t want to be sure what to make of it.

Is my controller holding state?

Yes. That’s a prime rule for a well formed MVC instance (an app written using MVC). The controller should hold no state. I would be so very delighted to announce that controllers cannot declare fields. Err, I’m afraid we started off declaring a view and a model field under our Control class. I’m sure you don’t think we are doomed yet.

But it’s not over. Now we’re ready to add ‘control states’. We’re also ready to write state machines. Yuk, see below.

I know you know. Call a rabbit a rabbit. These are states which belong to the control layer. Let’s add a control.model package. Unleash the Geek Inside.

Hyper-hacktivity

MVC naturals are incredibly hackable. That’s one of the things that got me writing tonight. I’ve been hacking an MVC instance mercilessly for 10 hours nigh. It’s very neat, because I spent three days this week trying to ‘rehabilitate’ the same app. Now I feel ready to start over. It’s good to be able to sort things out and release on time. But if I save one day every time I waste three, how good can it get?

Thinking about it, here’s one reason why MVC naturals are so hackable: statemessness.

  • Your GUI library is object oriented. It’s full of weeny controls that duplicate model state.
  • Your model is the primary state-holder. Surely the model knows (nearly) everything.
  • Your controller wouldn’t be so easy to write if you didn’t buffer a little state here and there.

Hackable. No matter where we’re writing code inside an MVC application, no state is ever far from us. Maybe not quite the right state, yet, in a first (and durably misleading) approximation, just about right.

Don’t hide behind your framework

MVC frameworks do that. If you look into their implementations, you’ll find that rules get broken. Basic rules. I see three solutions:

  1. Rules are for n00bs. The powerful magic behind singletons, static, event broadcasters and (while you’re at it) the C pre-processor is trickery that everyday coders should be interfaced with / insulated from, not exposed to.
  2. MVC frameworks are bad.
  3. The rules are bad.

Unit-testable or clear and concise?

I’ve been trying to put some of my latest MVC natural under unit test. Since I’ve been trying, and trying often leads me to explicit stuff I’d rather, for the sake of clarity, didn’t show up, I feel that natural MVC is biased against unit tests.

Inter-act

STOP.

By now, if you’re still reading you should probably go for a coffee break. Trust me. After all this article is just food for thought, not very thoughts.

Nice to see you back. Now that I’ve dusted around a little of the dust in the dust-bag, let’s muse a while into the muddle-dy swamp.

How things go wrong…

The shortest path is never the best path

Here are a few examples:

  1. It’s faster to emulate a button click than to separate action from reaction. The play button starts playback. The play menu item also starts playback. I want exactly the same thing to happen when I press the play menu item and when I press the play button. Sooo… I hack something up to pretend the play button was pressed when I hit the play menu item.
  2. It’s nearly always faster to pre-empt view updates. The controller knows what the view wants to do. The controller knows what the model will be like after we change it. In fact, the controller needn’t read the model, because the view reflects the model state faithfully enough… especially when we get started off and our view/model mapping is simple. I remember decomposing roundabout VCMCV routes using powerfully soporific sequence diagrams for the sake of principled colleagues. I also remember breaking my own rules and trying to explain what kind of risk is involved using whatever shortcuts.
    Now that I think about it…. (gasp) we don’t even need to update the model every time. That is, until auto-save stores a half-baked image of our data.
    Back to the original point: do we need a controller, or a model? Do we even need classes? Why not just use punchcards?
  3. Re-writing it is faster than just using it. MVC naturals tend to generate hierarchies. These hierarchies, more often than not, connect on an ad-hoc basis. Lay it out in UML:

    “it is 7:50 pm and you want to go home. You are ‘here’. The function you need is 10 clicks away on the class diagram and 3 steps are blocked because the hierarchy doesn’t back-wire. Re-write? Use a singleton? Introduce dependencies over 10 unrelated classes? Expose your lack of style and insight (russian doll message passing)?”

My button back-fired

Here’s a list widget. The user selects an item. A view event fires. The model updates.

Here’s a list. The list selection gets remotely updated. A model event fires. The list widget gets updated. A view event fires. The model gets updated. A model event fires…

Why is this happening all the time?

The inheritance delusion

It’s a text-book truth that inheritance isn’t an implementation level commodity. That’s probably why inheritance is hailed as a technique improving reusability and concision.

I took a controller this week; abstracted a base class off it. That simplified my coding four more, similar controllers. How are they similar? Well, they kind of work the same as the first one.

Truth is, I did it to save time and clarity. I’ve also seen what happens when we keep at it. Controller code isn’t especially concise. App controllers are meaningless idiosyncratic beasties anyway. Not your rationally bound mammal to mouse to cow inheritance anyway. If an app controller is a meaningless idiosyncratic beastie, what would an abstract app controller be? Or its grand-grandson?

Before you know it you’re abusing the decorator pattern. Classes implement functions for no reason, and nobody can understand a derived class until they’ve mastered five ancestors up the chain.

MVC naturals make it easy to use inheritance in this way. Or is it just inheritance that’s easier than delegation?

Your controllers are cursed down to the 13th generation. Amen.

The state machine delusion

Controller states are non committal. Unlike data-grave entries. Unlike serializable model data. Unlike view states, which at least, get rendered. Add a little flag here. Add an enum there. It doesn’t matter if two controller state-holders describe overlapping state. It can only hurt a little.

Here we are. It’s ‘kind of like a state machine’ just less complex and more complicated at the same time. However, all we need to keep ahead of it is a really good debugger. Well, I’d rather go and sink my own boat.

Until next time

It’s nothing like I’m done. I’m expecting staffing this experiment. As I stated at the beginning, there are many reasons not to go heavyweight. So I still need to find a way to get us sitting atop Pandora’s box. If there’s a way little bits of code mightn’t spiral out of control, looking for it is helping out, not brandishing glossy patterns no teenage coder would bother with.

A few months ago, I put quite a bit of work into understanding an MVC framework called PureMVC and getting a team up to speed using it.

I didn’t like the PureMVC thing too much because it’s so heavy. In this post I described a strategy for doing MVC with your own, home baked MVC pattern instance.

Do you bake MVC? Here’s a way to get your three layer cake from the designer’s pencil to the forge.

Ideal means this stuff is paperwork. I haven’t really tried it – but frankly speaking it’s mostly a simplification of what goes on in PureMVC, with a little bit of salt. Bon Appetit

An ideal MVC instance

In this model, the software is structured around three broad categories instantiated as packages.

  • View classes. View classes use some GUI API such as flash, java swing, OpenGL or the like. View classes also hold view specific data(1). When the user performs an action, such as clicking a button, the view handles this action by firing an event (see below).
  • Model classes. Model classes hold your application data.
  • Controller commands. A controller command is a command that changes the way the application reacts to events from the model and view, rather than changing the view and model directly. Typically, a controller command does nothing except register callbacks causing such or such event to trigger such or such command. Additionally…
    • Model actions are commands that change the model in some way. These commands operate only on the model. When the model has changed in some way, and we want to update the UI, the model needs to fire an event
    • The UI is controlled by UI update commands – commands that change the UI in some way. These commands operate only on the UI.

More about events

In the above model, note that neither view or model ever handles an event directly. This is not to avoid type dependencies, but to avoid conceptual dependencies:

  • Maybe an animation just finished in the view. If the model handles this event, the model is doing something based on the fact that an animation is complete. Even though the actual view type is hidden from the model, the model now requires making a big assumption about the view to operate.
  • Maybe the model changed in such or such way. It may be that this causes just one change in the view, but it maybe that the view needs to update in many ways, or it may be that we are using a general purpose view component that is used in combination with concurrent models.

Also note that a view or model doesn’t directly instantiate commands. This is consistent with the fact that the view shouldn’t know about the model (and vice versa). There are many cases in which it may be convenient and safe to allow the view to know about the model; however, this is a simplification of the ideal instance described here, so to stick to the general rule, the view should generate a SEND_MAIL event, even though it is obvious that this event maps to the SendMail command.

Lightweight versus heavyweight events

When writing your application, you will often need to send quite a bit of data along with an event – for example if a view needs to update a table, you need to send whatever needs to be updated along with your event, not just a message.

In this case, you have two choices:

  1. Use untyped event data. This is in some ways unsafe (more parsing/relying on implicit data formats), but it saves the trouble of defining additional structs or classes to store event data.
  2. Use typed event data. It is commendable to include event definition in a subpackage, e.g model.event, view.event

More about the event dispatcher

To make the above work, you need a kind of event dispatcher that can broadcast events to receivers. All your view/model classes should be able to access the dispatcher so that they can trigger events. Your control commands should be able to access the dispatcher so they can register callbacks.

It may be a good idea to expose the dispatcher to the view/model and the controller commands using a different interface. We don’t want view classes and model classes to modify our event to command bindings accidentally

ViewManager and ModelManager

When a command is instantiated, it needs to get hold of the data that it wants to manipulate. A simple way to allow this is to define singleton ViewManager and ModelManager. So for example the ViewManager contains all the views, and ModelManager is the root of the model’s data hierarchy.

How does the application start?

You may have noticed that it’s the job of command to specify bindings from events to commands. This leads to one of those chicken and egg problems – which one started it all? an event or a command. This doesn’t really matter, but here are two solutions anyway:

  1. Use a Main command. Then your framework needs some kind of bootstrap class that you call start() on.
  2. Invoke a command to bootstrap your application.

How to use the above while enforcing feature driven separation

It may be a good idea to combine your MVC pattern with some degree of feature driven separation (I wrote a lot about the F* Meta-Pattern and feature driven separation somewhere else). Here’s how a simple, non adventurous way to do it:

  • Break down your controller package into subpackages – one package per feature.
  • Use a controller command to register all the callbacks and commands related to each given feature. This is the ‘feature root’
  • Bundle additional commands required to realize your feature in the same sub-package as the feature root.

There are pros and contras to the above approach, compared to a typical F* instance:

  • PRO 1: In many existing workflows, we use WYSIWYG UI builders to generate our views. The original F* pattern typically requires moving back UI building into the code, because you need to be able to add widgets as part of feature code – in F*, your ‘send mail’ feature will require you to add the send mail button to a toolbar – that’s the price to pay if you want the UI to be correct once you have the removed the mail feature.
    This is further reflected in the way UI designers work. In cool applications, the UI is typically very integrated. Removing a function often means redesign in this case.
  • PRO 2: In many applications, most features rely on a core data model – i.e most of the data is used by several features. F* fragments your data model across features and leaves the generation of the core model as a refactoring exercise. There are many cases in which designing the data model as a self contained entity, adding stuff to it over time, maybe more efficient.
  • CON: F* allows you to delete a feature by deleting all related classes. With the above strategy, deleting the feature deletes only application functionality, not widgets and model data related to such functionality.

If you’re trying to write your first iPhone/iTouch applications or are struggling to put together a small to medium size application, this article may help.

This article assumes you have the ‘kind of understand’ feeling about MVC that most programmers get after digging up a little material on the topic.

A Basic Model View Controller (MVC) setup

In xcode, select new project > view based application. The following classes are created for a ‘Z’ project:

ZAppDelegate – Application Facade
ZViewController – Root controller

The only classes missing are a view class and a model class.

Basic view setup:

  • Create a ZView class if you need to customise the view provided by ZViewController.xib programmatically. Assign ZView as class of the root controller’s view from the property inspector in interface builder.
  • If you only want to gain access to UI elements added to the view, do the following:
  • 1 –  open ZViewController.xib and add your UI elements. In this example, I assume a label (UILabel class) was added.
    2 – add an IBOutlet field to ZViewController.h, like this :
    IBOutlet UILabel* myLabel;
    3 – In ZViewController.xib, notice that myLabel now appears in the file’s owner property inspector (click the blue arrow pointing right in prop inspector to view outlets). It has a little keyhole on the right.
    4 – From myLabel‘s keyhole, click-drag a connector to the actual label.

    Step 1 creates the actual UI element. Step 2 allows programmatic access to the created UI element. Finally, Steps 3 and 4 ensure that the field we have created maps to the actual UI element.

Basic Model Setup
Now suppose we created a ZModel class to hold our application data model. We probably want to gain access to the model from the controller. With a model driven view (view is mainly required to reflect model state), it is often convenient to keep a reference to the model from our view as well. This brings two questions:

1 – Where do we create the model? In other words, when should it be initialized?
2 – How do we provide the controller and view a reference to the model

These questions can be answered in various ways. For simple applications, here’s a recipe that works.

  • Instantiate your model class in ZAppDelegate::applicationDidFinishLaunching
  • Still in the same function, assign the model to the controller and view.

ZAppDelegate naturally owns a reference to the controller (viewController) and view (viewController.view). This makes it a convenient placeholder for our data model. Besides, even if we change the controller and/or view while the application is running, we can still access the model root. Finally, applicationDidFinishLaunching clearly holds the code used to add the view to the main window, so we are sure that the view binds the model before getting rendered the first time.

Processing user interaction

If your view is processing touches (touchesBegan etc…) it may be convenient to assign a backward reference from the view to the controller. Again, this setup can be effected from applicationDidFinishLaunching. We can then query the controller to perform high level actions when touches occur.
You can work around potential (compile-time) cyclical dependencies between the view and controller by only referring the controller using an
@class ZViewController
annotation before your interface declaration/class def. Although this may trigger a warning, you don’t need to import ZViewController to invoke methods on it as Objective C resolves method calls at runtime.

That’s it for now…

If your application is becoming complex, you may need to look into more developed MVC solutions – e.g. get inspiration from the PureMVC framework or maybe try my F* Meta-Pattern.