implementation of mvvm architecture in objective-c - ios

How to implement the mvvm architecture in objective-c ? I need sample project to learn the mvvm architecture and also i need to know that what is needed to give in model, view, viewModel and how to separate in objective-c ? what is the difference between the normal project and mvvm project ?

Jesto I can give you details about what you ask briefly.Even if it is explanation you can easily understand what I post here because it has sources with examples and you can directly try the source.
First the Model
The model layer is not as self-explanatory as it may seem.
As you would expect, it will have your model objects, potentially
covering most of the layer surface. In the tickets example, you would
have a Ticket struct that would live in your model.
I find the following components to also be part of the model layer:
Network Code. The shape should be something like this. Ideally, you’d only use a single class for network communication across your
entire app.
Persistence Code. You would implement this with Core Data or simply by saving an NSData blob directly to disk.
Parsing Code. Any objects that parse network responses and the like should be included in the Model layer as well.
While the model objects and the parser are domain-specific, the
network code will be highly reusable.
The controller will then use all the elements in your model layer to
define the flow of information in your app.
Second the View
When a user interacts with your app, they are interacting with the
view layer. The view is considered the “dumb” part of your app, since
it shouldn’t contain any business logic. In code terms, you’ll
normally see:
UIView subclasses. These range from a basic UIView to complex custom UI controls.
A UIViewController (arguably). Since a UIViewController is strongly coupled with its own root UIView and its different cycles
(loadView, viewDidLoad), I personally consider it to be part of this
layer, but not everyone agrees.
Animations and UIViewController transitions.
Classes that are part of UIKit/AppKit, Core Animation and Core Graphics.
Typical code smells found in this layer manifest in different ways,
but boil down to including anything unrelated to UI in your view
layer. A classic code smell is making a network call from a
UIViewController.
It’s tempting to put a bunch of code in your UIViewController and be
done with it, so you can meet that deadline. Don’t do it! In the short
term, you might save a couple of minutes, but in the long term, you
could lose hours looking for a bug, or have trouble when you want to
reuse code inside one view controller in another.
Third MVVM
Model-View-ViewModel, or MVVM, is an MVC derivation. Conceptually,
it’s similar. The biggest difference is in the communication between
layers, and instead of a controller, you use a view model.
In practice, MVVM shines when it has an FRP framework to support it.
Since the model is now observed by the view model and the view model
by the view, the FRP paradigm becomes a natural choice to manage the
information flow. This leads to a better separation between layers,
which translates in decoupled components that are easy to test.
Bottom line: architecture is important, but in my opinion the right
programming paradigm will influence more the overall quality of your
code. It’s also important to note, that most often that not, you will
have in the same app different approaches. This includes both
architecture and paradigm. You might think this will disrupt
consistency inside the codebase, but you should always use the right
tool for the job.
Finally MVC
The Model-View-Controller (MVC) design pattern assigns objects in an
application one of three roles: model, view, or controller. The
pattern defines not only the roles objects play in the application, it
defines the way objects communicate with each other. Each of the three
types of objects is separated from the others by abstract boundaries
and communicates with objects of the other types across those
boundaries. The collection of objects of a certain MVC type in an
application is sometimes referred to as a layer—for example, model
layer.
MVC is central to a good design for a Cocoa application. The benefits
of adopting this pattern are numerous. Many objects in these
applications tend to be more reusable, and their interfaces tend to be
better defined. Applications having an MVC design are also more easily
extensible than other applications. Moreover, many Cocoa technologies
and architectures are based on MVC and require that your custom
objects play one of the MVC roles.
Difference between Normal and MVVM
Models — responsible for the domain data or a data access layer
which manipulates the data, think of ‘Person’ or ‘PersonDataProvider’
classes.
Views — responsible for the presentation layer (GUI), for iOS environment think of everything starting with ‘UI’ prefix.
Controller/Presenter/ViewModel — the glue or the mediator between the Model and the View, in general responsible for altering the Model
by reacting to the user’s actions performed on the View and updating
the View with changes from the Model.
MVVM Says
The latest and the greatest of the MV(X) kind The MVVM is the newest
of MV(X) kind thus, let’s hope it emerged taking into account problems
MV(X) was facing previously. In theory the Model-View-ViewModel looks
very good. The View and the Model are already familiar to us, but also
the Mediator, represented as the View Model. MVVM It is pretty similar
to the MVP:
the MVVM treats the view controller as the View
There is no tight coupling between the View and the Model In addition, it does binding like the Supervising version of the MVP;
however, this time not between the View and the Model, but between the
View and the View Model. So what is the View Model in the iOS reality?
It is basically UIKit independent representation of your View and its
state. The View Model invokes changes in the Model and updates itself
with the updated Model, and since we have a binding between the View
and the View Model, the first is updated accordingly.
Also the MVVM Design Pattern and How does MVVM work?

Check it out this topic -> What is the difference between MVC and MVVM?
Model-View-ViewModel basic example is here -> https://github.com/futurice/mvvm-example-objc and maybe next step, you can use reactive cocoa because it can be more effective with mvvm -> https://github.com/ReactiveCocoa/ReactiveViewModel
reactive cocoa -> https://github.com/ReactiveCocoa/ReactiveCocoa
goodluck :)

Related

Choosing generalisation or association (aggregation)

My IOS application includes similar views that draws data from server and visualise them.
I want to combine common networking code in a class to ensure reusability and to avoid repeated code.
Should I locate networking code in a super class or in an associated class. I couldn't make a decision which method should I use, generalisation or association (aggregation)?
What would you do if you were me?
It is not good solution to create view superclass for storing client-server communication code due causes:
Client-server communication isn't a part of data presentation (View). Logically it is separate entity.
If you use associated object you could use it anywhere, not only in Views that represent loaded data. It makes your architecture more flexible.
There are more reasons to not use inheritance in your case but I think these two points are enough to make decision.
To my mind you should use associated object (aggregation).

Model-Controller Abstraction with Core Data

In learning about Core Data, I've noticed how (in Xcode's templates) Apple directly used the query classes inside the view controller. This seems like it is bad MVC (having database access logic directly inside the view controller). Would it make sense to abstract out these kinds of actions to a separate suite of classes that obtain the data from the database and pass it back to the view controller calling it?
EDIT–
So, just to be clear, when I say "kinds of actions", I specifically mean CRUD Operations. Though if you have ideas about other things that a so-called "Model-Controller" would do, I'd be interested in hearing about them.
It's a matter of opinion, and often yes the templates are the most simple form of working example. It's hard to have a template spin out multiple files, for example.
Yes, personally, I generally spin out a separate NSManagedObject subclass. I like to have a _MySubclass object that has all the auto-generated stuff, then have the model actually reference MySubclass which has model-based business logic (you can use mogenerator or other methods to do this too if so inclined). Perhaps thinking of it as "Model-Controllers" and "View-Controllers" is another way of putting it.
This is a very good question and the answer likely depends on your situation. Perhaps architecture purists would insist on separate Model controllers and there are a lot of benefits to this approach. However, sometimes I find myself using Key Values when I'm doing a simple view. When things are more complex, for example, when coding the same Model for the Mac and iOS, having separate Model Controllers will allow you to reuse a lot of code. When you must diverge, Obj C Categories are a very clean way to extend functionality without adding a lot of overhead. I personally favor categories over extensive subclassing.
Since NSFetchedResultsController was released, my model classes are leaner. There are a lot of nuances to this and experience will help you come up with the best solution for your App. I've also found that writing unit tests up front will help you force through issues and validate your design, or send you back to the drawing board :)

What are the best practices for Asp.net MVC page construction, allowing for parallelism and efficiency?

I found it difficult to argue with anything in this critique of ASP.net MVC's framework for page composition.
http://www.matlus.com/problems-with-asp-net-mvc-framework-design/
Particularly these points:
No access to view or partial view instances
ViewData is your loosely typed information carrier
Controller is not really in control
Child Actions have no sense of the Request Context
Views are coupled to controllers
For small applications, I don't think that a lot of these prove to be much of a problem, but in large applications where you want to reuse a lot of shared components, or even if you just have a large application that depends on multiple backend sources of information to obtain all of the information necessary to render a view, it starts to break down.
Various half-solutions to these problems have been proposed but they do not appear to scale well or have undesirable design constraints.
Here is an example application scenario:
50% of page content is common across all pages within an application (header, footer, menus, etc.)
Your application may actually be comprised of multiple areas, each with their own controllers, etc. for independent development.
A number of the page elements (menus, page header information, footers, disclosures) that are in the common page content require one or more service calls to fill out the data for rendering.
Okay, so in asp.net mvc3, let's say that you decide that you want to share a common Razor layout that contains the 50% common UI markup. This assists with Separation of Concerns in that application developers don't need to be concerned about common ui and can focus on the logic and views specific to their domain of expertise.
However, this completely breaks down in the case that this shared layout needs data (some semblance of one or more model types) to render itself completely. You may have independent elements on the page that each need a particular data model, such as:
* primary menu model
* secondary menu model
* footer links model
* authorization model
* footer disclaimers model
And each of these models may have separate sources. So although you can share the template, there is not an easy way to share the logic to build each of these models -- and there is definitely not one that is generic, extensible, and performant that I have seen.
Some approaches to this problem that I have seen are:
Strongly type the common layout, which requires all view models to subclass a common base model class. (but there is no general solution to populating such a meta-model, and this is limiting in design and makes models huge and harder to test) Additionally, model population still falls to every controller, violating the Separation of Concerns and Single Responsibility Principle and complicating unit testing controllers by piling on lots of extra logic to populate the meta-model in addition to the view-specific model information.
Leave the common layout untyped, so you don't have to inherit from a common base model, but this requires you to use ViewData or ViewBag to communicate all of the disparate models that the template needs so you lose strong typing benefits and end up with a loose data contract. You still have the problem of a lack of a general solution to populating the meta-model and all that goes along with that.
Every controller has to subclass a common base controller class to support a common layout and model. Logic for building the common aspects of the meta-model goes here. But this is not always a desirable architecture or design constraint. This does at least resolve the Separation of Concerns issues.
Instead of a meta-model, use child actions via RenderAction() in your common layout to make reusable "portlet" style widgets that each know independently how to build their data model and provide it to their view. This is really good for Separation of Concerns, but has its own litany of downsides: views effectively making service calls during rendering via the child actions, child actions are completely unaware of the original request context, violates DRY principle as each child action is unaware of what has gone before it so each could make the same service calls over and over again in the same http request, and others. Imagine 20-30 elements of a page that all needed to invoke RenderAction() independently...
There are additional cases (some seen on stackoverflow as well) where there are other problems with RenderAction() as a solution. e.g. the fact that issuing multiple RenderAction() calls in a loop results in serial execution of all of those controller methods. There is no opportunity for parallelism with RenderAction(). I/O bound service calls in each child controller action cause the whole rendering process to wait on I/O. A controller only has knowledge of its immediate view and model and nothing has a complete picture of what is going to be inside the view in order to parallelize some operations.
The author of the above critique developed a different UI model on top of ASP.Net mvc called Quartz that allows a God Controller to have intimate knowledge of the views and can hand each of them a view model so has the opportunity to parallelize service calls in a central place to build those view models. I don't know if this is the best design to provide hooks for overcoming the problems but looks promising.
My question is, what is the best practice for building a complex application on top of ASP.Net MVC that cleanly solves these problems? I have thought of a couple possibilities (although none may be practical within ASP.Net MVC--that is TBD) but someone else must have ran into this already. What are the design patterns within ASP.Net MVC or what is coming down the pike that could make this a tractable problem?
Personally, I think that the advantages of using Child Actions via RenderAction outweigh the disadvantages.
You can create 'widget' sort of elements, and wrap up their logic in a controller action - this way the view calling the widget can remain quite ignorant of what the Child Action is doing and how it is doing it - leading to a nice separation of concerns.
You have detailed the disadvantages of this approach, however I think that the negative impact can be minimised with a reasonable caching strategy.
I'm not sure there's really much more I can contribute to this "question". I think you have a good understanding of the problems and solutions, advantages and disadvantages.
In the app I'm currently working on, we utilize a couple of these approaches by having both a base model object as well as a base controller. In order to minimize roundtrips, we store some data in session and re-populate in the model by overriding the OnActionExecuted in the base controller and grab the model out of the context and set properties out of session.
I'd certainly like to hear any wonderful solutions as well, but I think these are just the tradeoffs to deal with.

ASP.NET MVC best practices using EntityFramework and mapped ViewModels

I've never worked with MVC design pattern before and recently I started to work on the project using ASP.NET MVC.
I'm using ActiveRecord as my data layer.
I'm also using view models (unique for each view) and AutoMapper to map my view models to EntityFramework entities.
In a few days reseaching about MVC, EntityFramework and reading different articles I came up with the following design:
In my solution I have Web project (Presentation Layer) which contains Views and Controllers.
I have Core project where I define my ViewModels and Services (Business layer where all business logic goes)
I have EntityModels project where all me EF entities live (Data layer)
This design allows me to keep my Data layer separate from my Presentation layer, Web project doesn't know anything about EntityModels project and vise versa, all the logic lives in business layer.
From my controllers (after validation checks) I pass viewModels to Service layer where mapping and all necessary busines logic is executed.
Is this design correct at all?
My consern is that I've read that ViewModels should be defined in Presentation Layer. I saw examples where Presentation Layer has references to Data layer and mapping is done in controllers (good practice?). in this case controllers pass domain models to business layer. I don't have any experience here but I don't like it.
So, can anyone point out where I'm right and where wrong?
thanks in advance.
Overall the architecture looks good. The decision on where to place you view models hinges on one factor in my opinion.
Do you plan to have other clients in the future that may benefit from reusing those view models (iPad, Android, etc.)?
If so, definitely keep them out of the MVC assembly and put them in their own assembly. Otherwise, you're safe putting them in the MVC app as long as you're ok with moving them and changing code if you ever decide to make a second client.
For the record, I always put my view models in their own assembly. It doesn't take more time up front, but it pays dividends down the road if things change.
FWIW, I am doing the same thing - but I am new to MVC, so not 100% sure I'm on the right path also. But, it just "feels right", which more often than not tells me it is correct.
The only thing I would add is that I use automapper (automapper.org), which almost eliminates the overhead of having the layers. Definitely check it out IMO.
I have to say the only thing that doesnt feel 100% correct is that with this pattern, we are creating a whole lot of ViewModels -> one per View. I assume you mean that Create, Index, Update, Details for each domain entity EACH have their own ViewModel? Or are you sharing one ViewModel between the views?
Lastly, I dont buy jfars argument that it creates lots of complexity/build time. At the very least, it conceptually separates the layers that much more. It strikes me as a much better job of separating the concerns, with very little overhead.
I have a pipe dream of reusing the viewmodels for a silverlight implementation, but havent really thought that one through yet. But it makes sense that if you do a good job of factoring out all "non-UI" code into the viewmodels and services, then doing a new UI should be "trivial", right? we'll see :-)

Does Model-View-Controller Play Nicely with Artificial Intelligence and Behavior Trees?

I come from an MVC background (Flex and Rails) and love the ideas of code separation, reusability, encapsulation, etc. It makes it easy to build things quickly and reuse components in other projects. However, it has been very difficult to stick with the MVC principles when trying to build complex, state-driven, asynchronous, animated applications.
I am trying to create animated transitions between many nested views in an application, and it got me thinking about whether or not I was misleading myself... Can you apply principles from MVC to principles from Artificial Intelligence (Behavior-Trees, Hierarchical State Machines, Nested States), like Games? Do those two disciplines play nicely together?
It's very easy to keep the views/graphics ignorant of anything outside of themselves when things are static, like with an HTML CMS system or whatever. But when you start adding complex state-driven transitions, it seems like everything needs to know about everything else, and the MVC almost gets in the way. What do you think?
Update:
An example. Well right now I am working on a website in Flex. I have come to the conclusion that in order to properly animate every nested element in the application, I have to think of them as AI Agents. Each "View", then, has it's own Behavior Tree. That is, it performs an action (shows and hides itself) based on the context (what the selected data is, etc.). In order to do that, I need a ViewController type thing, I'm calling it a Presenter. So I have a View (the graphics laid out in MXML), a Presenter (defining the animations and actions the View can take based on the state and nested states of the application), and a Presentation Model to present the data to the View (through the presenter). I also have Models for value objects and Controllers for handling URLs and database calls etc... all the normal static/html-like MVC stuff.
For a while there I was trying to figure out how to structure these "agents" such that they could respond to their surrounding context (what's selected, etc.). It seemed like everything needed to be aware of everything else. And then I read about a Path/Navigation Table/List for games and immediately thought they have a centrally-stored table of all precalculated actions every agent can take. So that got me wondering how they actually structure their code.
All of the 3D video game stuff is a big secret, and a lot of it from what I see is done with a graphical UI/editor, like defining behavior trees. So I'm wondering if they use some sort of MVC to structure how their agents respond to the environment, and how they keep their code modular and encapsulated.
"Can you apply principles from MVC to
principles from Artificial
Intelligence (Behavior-Trees,
Hierarchical State Machines, Nested
States), like Games?"
Of course. 99.9% of the AI is purely in the Model. The Controller sends the inputs to it, the View is how you represent it on the screen to the user.
Now, if you want to start having the AI control something, you may end up nesting the concepts, and your game 'model' contains a Model for an entity, a Controller for the entity which is the AI sending commands to it, and a View for the entity which represents the perceptions of that entity that the Controller can work with. But that's a separate issue from whether it can 'play nicely'. MVC is about separating presentation and input from logic and state and that aspect doesn't care what the logic and state looks like.
Keep this in mind:
The things which need to react simply have to be aware of the things to which they need to react.
So if they need to know about everything, then they need to know about everything.
Otherwise, -how- do you make them aware? In 3D video games stuff, say first-person shooters, the enemies react to sound and sight (footsteps / gunshots and you / dead bodies, for instance). Note that I indicated an abstract basis, and parts of the decision tree.
It might be wrong in your specific case to separate the whole thing between several agents, and simpler to leave it to one main agent who can delegate orders to separate processes (/begin babble) : each view could be a process which could be told to switch to any (a number of) view by the main agent, depending on what data the main agent has received.
Hope that helps.. Take it all with a grain of salt :)
It sounds like you need to make more use of the Observer/Event Aggregator pattern. If multiple components need to react to arbitrary application events without introducing undue coupling, then using an event aggregator would help you out. Example: when an item is selected, an application event is published, relevant controllers tell their view to run animations, etc. Different components aren't aware of others, they just listen for common events.
Also, the code that makes the view do things (launch animation depending on model/controller state) - that's part of the View itself, so you don't have to make your architecture weird by having a controller and a viewcontroller. If it's UI specific code, then it's part of the view. I'm not familiar with Flex, but in WPF/Silverlight, stuff like that would go into the code-behind (though for the most part Visual State Manager is more than enough to deal with state animations so you can keep everything in XAML).

Resources