MVC in iphone apps - iphone

can somebody explain me the basics of mvc in iphone apps?
I see the template classes, but how do they communicate?
does UIView send events to the Controller? or does the model send events?
what of the template files is the model?

I would strongly recommend the iTunesU, Stanford University series titled "Developing Apps for iOS (HD)" by Paul Hegarty.
Lesson 1 discusses MVC and lesson 2 demonstrates it.
These lessons are free, and well worth a view if you have the time.

The model shouldn't be concerned with the view. The same holds true for the view, it should be decoupled from the model and not really have direct access to it, despite the fact it will be displaying information from the model for the user to see and interact with. The controller acts as intermediary between models and views.
In Apple's words, "A controller object interprets user actions made in view objects and communicates new or changed data to the model layer. When model objects change, a controller object communicates that new model data to the view objects so that they can display it."

From Jeff Atwood's Excellent blog "Coding Horrors":
Like everything else in software
engineering, it seems, the concept of
Model-View-Controller was originally
invented by Smalltalk programmers.
More specifically, it was invented by
one Smalltalk programmer, Trygve
Reenskaug. Trygve maintains a page
that explains the history of MVC in
his own words. He arrives at these
definitions in a paper he published on
December 10th, 1979:
Models Models represent knowledge. A
model could be a single object (rather
uninteresting), or it could be some
structure of objects.
There should be a one-to-one
correspondence between the model and
its parts on the one hand, and the
represented world as perceived by the
owner of the model on the other hand.
Views A view is a (visual)
representation of its model. It would
ordinarily highlight certain
attributes of the model and suppress
others. It is thus acting as a
presentation filter.
A view is attached to its model (or
model part) and gets the data
necessary for the presentation from
the model by asking questions. It may
also update the model by sending
appropriate messages. All these
questions and messages have to be in
the terminology of the model, the view
will therefore have to know the
semantics of the attributes of the
model it represents.
Controllers A controller is the link
between a user and the system. It
provides the user with input by
arranging for relevant views to
present themselves in appropriate
places on the screen. It provides
means for user output by presenting
the user with menus or other means of
giving commands and data. The
controller receives such user output,
translates it into the appropriate
messages and pass these messages on to
one or more of the views.
The best way to understand this (like many core concepts of iOS programming cough HIG cough), is to read Apple's documentation and try it. Here is a good design pattern overview (including MVC) for beginners, including a tutorial: Link

Related

MVVM, UWP & Template 10 - Independency of model from view technology

My understading of MVVM is that View is responsible for user presentation logic, view-model for interaction logic and specific data transformation from UI independent model classes and model itself representing business domain from data point of view.
Key point is that model classes should be UI indenpendent.
Here comes UWP dev model and Template 10 BindableBase from which model classes are supposed to be derived from. It's quite handy but it ties the model to the specific UI implementation, namely UWP + Template 10.
I've got a data access layer spitting out domain object I want to feed directly as model to the UI. The domain is quite complicated. What I don't wan't to do is to reimplement data domain objects in the UI nor I wan't to pollute it with UI specific functions.
Any thoughts on this?
thank you
With all due respect, I think you might be thinking about this wrong.
The goal of MVVM is to separate your logic exactly like you describe. The intent of this separation is to simplify your code. Does this make view-models testable and separate concerns? Yes. But, I argue those are secondary goals to simplicity – which keeps your code manageable and maintainable.
Here’s another way to say it.
MVVM is a terrific approach for XAML applications. But, if MVVM did not make your view-models testable or separate concerns, MVVM is still a terrific approach for XAML applications because it simplifies code so much – smaller, simpler, and isolated.
Worth every penny.
You might argue that MVVM creates another layer of code that developers must understand before they can reason and contribute to the base. I would agree. But I would NOT conclude that MVVM is therefore impracticable. That added layer is trivial compared to the otherwise coupling of logic.
Now to your question.
Your data layer object, probably a data transfer object, is remarkably like your UI object, probably a model. Your developer instincts compel you to unite similar things through polymorphism, code generation, or interfaces to avoid added opportunity for bugs, complexity, and tests.
Consider this.
Objects created in your data layer are created for your data layer. Likewise, objects created in your UI layer are created for your UI layer. Similarity in structure is a byproduct of similarity in domain. Of course, they are similar: their intents, however, are not. Why would you merge them?
You already see the problem.
The only differences you have are, perhaps, a data layer constructor taking in some type of data reader and populating properties. That is perfect for the data layer but inappropriate for the UI layer. Your UI layer might have messaging events or a custom method to handle interaction. That is perfect for the UI layer but inappropriate for the data layer.
So, where’s the similarity?
I think developers, including myself, tend to see similar things as potentially identical. Your data-relevant features do not belong in your UI nor the other way. Instead what you need to do is to see the similarity but recognize that they are drastically different objects and don’t deserve to be made the same.
We’re lazy.
Duplicate code isn’t about tests and bugs. Not really. It’s about how we, as developers, are so obsessed with “Work smarter not harder” that we tend to look down on “working hard”. If an object is built for one layer it should be in that layer, and not shared by another. I strongly feel this way.
The right solution
The easiest solution is to let your DTO serialize on the data layer from DataLayer.Object and then deserialize it on the UI layer as UILayer.Model. This is the easiest and simplest approach and adequately allows you to coerce the data and the object API for the use by its unique layer.
This means there are two nearly identical objects: one on the data layer and one on the UI layer. But it does NOT mean there are two identical objects. They are not identical because they have functionality unique to each of the tiers, each of the layers.
What if there is no functionality?
It makes sense to wonder if this applies to objects and models that have no added functionality. I believe strongly that objects and models in any layer without added functionality are simply waiting for that functionality to be added. Should you assume there is none and build to that assumption, you force the future you or forthcoming maintenance developers to never add layer-specific functionality.
Does that matter?
I think it does. Why? Because layer-specific functionality in an object or model allows me to add sophistication (not complexity) to my architecture and implementation within the context of the data object or model, and not in an external construct like a manager, helper, or utility. There is no question that Type.DoSomething is easier than Helper.DoSomethingForType(Type).
I actually have three
Just so you know, here’s how I do it: in my projects, you and I probably have similar data layers/services. But, my UI layer actually has TWO models – not one. (Let’s pretend Users is the data type.) My UI layer has json.User and Models.User. The json.User is a bare bones structure, deserialized from my service, and matches the service object exactly. But my UI rarely needs the Service API surface/structure.
Service(DataLayer.User) > | net | > UI(json.User > Models.User)
So, then json.User is used to create Model.User, whose structure meets my UI layer’s needs exactly - including methods, events, and messaging constructs. I am free to change my Models.User as I add features to my UI, too - including merging data from other/new data services. Also, Model.User can implement INotifyPropertyChanged where the data layer objects and the json objects never would (or need to).
Consider this
If you keep your models separate and you keep one codebase from improperly influencing another, then any change in your database or change in your data service/layer does not REQUIRE a change in your UI layer, even if you change the API surface. Only json.User changes or tweaks to your deserialization hints in your UI layer are impacted. To me, this only makes sense.
But what about testing and bugs?
Tests rarely test structures. Data structures are the simplest thing you can add to a solution and rarely contribute to complexity. You can reason over a structure in about a second. You can reason over a method in about a minute. Structures have very little cost. They also have very little construction cost. If you copy/paste the initial structure from your data layer to your UI layer – that’s what we all do. But that is NOT duplicating code. It is just building similar objects appropriately decoupled.
That’s what I think.

MVC in Cocoa Touch

I'm having troubles understanding if I'm properly implementing the MVC pattern in an iPhone app. In my app I have views, view controllers and models. The view controllers manage the interfaces, navigate to other view controllers, set variables to other view controllers and models, and communicate with the models. But this way, am I correctly following the MVC pattern? Don't I miss a model controller?
Another question: I have a User Model that I need to have access to in almost every models and some controllers. Would it be correct to define it as a variable in the appDelegate? I'm all the time reading that this is a bad practice, but I don't see why in this case.
Global objects
All non trivial code has bugs, and they are harder to track if you use dumb global objects. By "dumb" I mean generic objects from the API that lack a single point of access in case you need to log, validate, key-value observe, and notify, changes. You can wrap the global object in a class to route everything through your own accessors.
Some say using globals at all gets you into a bad habit. Others say it depends on the size of your code because it is a trade between development speed and complexity.
The appdelegate is a Singleton, so this discussion is related: What is so bad about singletons? and Singletons: good design or a crutch?.
MVC
Apple talks about it in Cocoa Core Competencies and Cocoa Fundamentals Guide.
One can merge the MVC roles played by
an object, making an object, for
example, fulfill both the controller
and view roles—in which case, it would
be called a view controller. In the
same way, you can also have
model-controller objects. For some
applications, combining roles like
this is an acceptable design.
Is your design complex enough to need a model controller? Whatever your decission is, suffering the consequences will teach you a lot. :)
A design pattern in which the model (any data in your program), the view (what the user sees), and the controller (a layer that handles all interaction between the view and model) are separated in such a manner that modifying either the view or model component of your program has no effect on one another.
The purpose:
The purpose is that later on you may need to change your programs view, and by programming things in this matter you will not have to modify your programs model. Say for instance Apple comes out with an iPad for which the view is programmed somewhat differently than on the iPhone, but you would like to
Now I received some messages after making the video above, some thanking me for making the concept of MVC sound so simple, and others telling me that I had confused them, and wondering how I could understand any of this stuff.
Well, don’t fret.. I’ve seen arguments all over the place as to what components should be classified in the model, the view, or the controller, and I’ve even seen accomplished "guru authors" mess things up when explaining what goes where, just keep in mind that the key idea here is that you can modify one of these key areas without completely wrecking another key area of your program, and leave the rants to the wannabe coders who like to argue about what exactly what fits what acronym, and MVC is often their target.

Create an 'order' file on iPad/Objective C w/ auto mailer

I'm currently designing a restaurant based menu system of iPad with the basic functionality of being able to view items on the menu, then add them to an order, be able to review the order (with the possibility of removing them) then finalising a price and (time permitting) be able to email the order to a specific email address.
Currently I have a split table view with each section of the menu, pictures and text. I am at a roadblock where I can't see how I can proceed with the project.
Firstly, if I have an 'add to order button' underneath the item description, how can I create a new list (or order), how do I display it/edit it?
I'm really stuck as I see no logical way to do this.
Any help or pointers would be greatly appreciated.
I'm not sure of your mileage with the Cocoa APIs, but it sound like you are missing some fundamental knowledge about how to effectively work with them. Primarily, I am speaking about the contents of the Cocoa Fundamentals Guide, Model-View-Controller Design Pattern section.
To me, it sounds like you have made good progress on getting the view component of that design pattern, and you are at the point of fleshing out the model and the controller. If you don't understand the terminology, the model essentially encapsulates all of the objects that constitute the domain, which in your case is is "restaurant-based menu systems". Then, the controller piece is concerned with shuffling data from your model to your view and also other general application logic.
Without further requirements about what type of data your app should be concerned with, it's hard to advise you on what you need. You probably want a set of objects that align with the nouns (like Menu, MenuItem, Order, etc.). Then, those objects would have methods that determine how they interact with each other.
Lastly, the controllers (of which you should already have some in your project if you used the Xcode templates) should have a way to manipulate the aforementioned model objects and present the data. The list you mentioned could be something as simple as an Order object which has an NSArray of MenuItems that have been ordered.
So, ultimately my advice would be to read through the Model-View-Controller section in the Fundamentals guide and once you understand it, try creating a model that supports what it is you are trying to achieve. Diagrams or sketches that depict the objects and their interaction help with this. Then once you have done that, you can start to wire your model up with your interface in the controller. Hope this helps.
There are a few things you are asking here:
Adding an item to an order. This implies a purchase cart like solution. These can be quite complex. I'd start with a simple list (NSArray of item numbers?).
How to display this list. This would be the visual aspect of the cart. Just think of this as a menu table like you currently have, but with the cart array as a filter.
Emailing this information. This is surprisingly easy. Present a modal MFMailComposeViewController after adding a text version of your order as the messageBody.
A further idea would be to expand the cart to use menu item objects that you design in core data. You might also have luck hunting around for a library that encapsulates the needs of the cart for you.
Hope that helps.

Get rid of proxy properties in the VM?

I am learning MVVM now and I understand few things (more than but few are here..):
Does every model potentially exposed (thru a VM) to the View is having a VM?
For example, if I have a Contact and Address entity and each contact has an Addresses (many) property, does it mean I have to create a ContactViewModel and an AddressViewModel etc.?
Do I have to redeclare all the properties of the Model again in the ViewModel (i.e. FirstName, LastName blah blah)? why not have a ViewModelBase and the ContactViewMode will be a subclass of ViewModelBase accessing the Entity's properties itself? and if this is a bad idea that the View has access to the entity (please explain why), then why not have the ViewModelBase be a DynamicObject (view the Dictionary example # the link page), so I don't have to redeclare all the properties and validation over and over in the two tiers (M & VM) - because really, the View is anyway accessing the ViewModel's fields via reflection anyway.
I think MVVM was the hardest technology I've ever learned. it doesn't have out-the-box support and there are to many frameworks and methods to achieve it, and in the other hand there is no arranged way to learn it (as MVC for instance), learning MVVM means browsing and surfing around trying to figure out what's better. Bottom line, what I mean by this section is please go and vote to MSFT to add MVVM support in the BCL and generators for VMs and Vs according to the Ms.
Thanks
What a telepathy!
I enjoyed so much reading this great article of Robert McCarter's, he talked just about what I felt painful with! especially about the proxy-properties (now I even know it's name...).
I would warmly recommend this article to every MVVM confusee (like me - I am sure there are a lot!)
1/2) Like with most programming problems... It all depends.
It depends upon how you've linked together the ideas. You can re-expose the needed model properties in the view model if it fits your needs. Hide model proporties that you don't want the user to interact with like a DB key. You can put the model validation logic in the model or the view model. It all depends on what works for you and your situation, which is why it is hard to directly answer the question.
I am using the ViewModelBase for functionality shared by ALL of the ViewModels. I've been using the base object to handle INotifyPropertyChanged code and little else.
3) Take a look at Karl Shifflett’s web site. Karl has a bunch of code you can look at. Stuff and BBQ Shack are working MVVM projects. He also has a complete MVVM training module here.
I'd post some links, but I'm limited to 2 links per post.

Web framework programming mindset [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I am just starting to play with Django/Python and am trying to shift into the MTV mode of programming that Django asks for (insists on). Deciding on what functions should be methods of a model vs simple being a function in a view has so far been confusing. Does anyone know of a book, website, blog, slideshow, whatever that discusses Web Framework programming in more general, abstract terms? I imagine just a book on object oriented programming would do it, but I feel like that would be overkill - I was looking for something web framework specific.
My basic rule in Django is: if you could conceivably need the functionality from somewhere other than the view itself, it doesn't belong in the view function.
I'd also recommend downloading some of the plethora of apps on Django Pluggables and seeing how they do it.
Once you do find some good guide, here's something to remember: Django is a bit special with its terminology. It uses "MTV" for Model, Template and View (and can mention also a URL Dispatcher somewhere along the way), whereas a more standard set of terms is "MVC" for Model, View and Controller.
Model is the same in both meanings - a model of a data entity, often linked to a database table, if the framework implements Object/Relational Mapping (which Django does).
But the two remaining terms might be confusing; where Django talks about Views, the 'rest of the world' talks about Controllers. The basic idea is that this is where the presentation logic is done. Calculations are calculated, arrays are sorted, data is retrieved, etc. I'd say that Django's URL dispatcher is also a part of the conventional Controller concept.
Django's Templates are comparable to Views elsewhere - here you have your presentation, nothing else. Where Django forces you to a very small set of logical commands, other frameworks often just recommend you not to do anything than present HTML, with some presentation logical elements (like loops, branches, etc), but don't stop you from doing other stuff.
So, to recap:
Model: Data objects
Controller (View in Django): Data process
View (Template in Django): Presentation
Oh, btw: For a Django-specific guide, consider reading The Django Book
I've not really used Django in anger before, but in Rails and CakePHP (and by extension, any MVC web-framework) the Fat Model, Skinny Controller approach to organising your methods has been a real eye-opener for me.
If you aren't absolutely set on diving into Django and don't mind trying something else as a start, you might want to give WSGI a shot, which allows you to template your application your own way using a third party engine, rather than having to go exactly by Django's rules. This also allows you to peek at a lower level of handling requests, so you get a bit better understanding of what Django is doing under the hood.
Here are a few links that might be helpful as an overview.
From my own experience, when I first started using MVC based web-frameworks the biggest issue I had was with the Models. Prying SQL out of my fingers and making me use Objects just felt strange. Once I started thinking of my data as Objects instead of SELECT statements it started getting easier.
MVC In laymen's terms
MVC: The Most Vexing Conundrum
How to use Model-View-Controller
View function should only contain display helpers or display logic. View functions should never access the model itself, but should take parameters of model data. It is important to separate the model from the view. So if the function handles accessing the database or database objects, it belongs in the model. If the function handles formatting display, it belongs in the view.