Model view advice needed - model-view-controller

I have been stuck for so long on this and just can not get my head around the concept. I cant retain any data outside my first page on my apps, every-time I push to another view I lose all my data entered in text fields or any pictures imported. This means I have do do everything on the first page as that the only page that dosent destroy data as soon as i move away from it.. Surely there must be an easier way to do this...can someone point in the direction of a real beginners guide to model views, ive read Apple's documentation on this and find it no help at all, ive read up on here, and googled it and really am running out of ideas now

You are storing your data in the "Controller" level. Like the "View" level these come and go and are not a good place to store data long term. For longer term storage you want to keep you data down in the "Model". You can think of the three tiers this way.
The Model is the data (both volatile and permanent) and business rules.
The Controller is business rules, data interpretation to and from the view to the model, and user interaction management.
The View is for data output translation to meaningful information and user response interpretation.
Controllers (View Controllers) should only hold enough data to do their job and should never be considered to hold data any longer than is necessary. This is why the original view controller is the only one that keeps the data. It is the "Root" view controller and is not removed since it is the bottom view controller. When you "push" another view controller it is temporary because it will be "popped" back off and deallocated. Consider keeping your data (even for you root view controller) someplace else where you can get to it. Maybe in the App Delegate, Core Data, or a custom class that simply manages the data you need. Ensure your Model and Controller object can get to the data and you will have consistent data.

Related

Core-data raises "The file has been changed by another application"

When changing data in my core-data application, a error message comes up:
The document “xyz.sqlite” could not be saved. The file has been
changed by another application.
In fact, there is no other application that has changed data. I observed in addition, that the undo management is not working well then.
Probably, I should not use more than one (unique?) Arraycontroller bound to the managedObjectContext for one entity ?
In my app, I use a classical master-detail relationship setup with 2 controllers for each entity - and 2 table views to display the data.
But, in addition I want to present a list of all details, where I can change the master. Therefore, I am using another Array controller bound to the same managedObjectContext. This one does not have a content set to the master, so it will have all detail objects. Using this approach makes it easy to manage the relationship in the associated tableview (by simply binding "selected Object" to the relationship of the detail) - but it seems to impact the app.
Does anybody else face this issue ? Any idea is welcome !
Core Data on the Mac has never dealt well with multiple programmatic changes to the underlying data, especially in document-based apps. See, for example, autosavesInPlace causes New Document save to fail.
I think you're on the right track by using the same MOC for all of your views. If you use multiple MOCs, you ave the risk of getting the data out of sync between views. Using Cocoa Bindings on the array controllers ought to be keeping everything in sync.
Is there a situation where you're making programmatic changes to the data in the background? Those should probably be done in a child of the viewContext. Or take other steps to make sure they get synced to the viewContext.

MVC: Where should I put this data access logic?

I've been trying to adhere to a strict interpretation of MVC in rebuilding a personal web application at home, but I'm having some issues.
The application is a financial tracking application. I'm stuck at the first page, which is just a list of the bank account transactions for the month. The transaction list is my Model. The Controller and View are easy enough to envision at this point.
However, I also have two buttons at the top of the page. They are arrows, one corresponding to the previous month, and the other corresponding to the next month's transaction list. I don't want these buttons enabled if there are no transactions for the previous/next month, so I need to talk to the database to figure out whether each button should actually link somewhere.
From most of what I've read, to the largest extent possible database access should be encapsulated in models, with little to no database access in Controllers and Views.
However, these buttons essentially need to ask the database, "Are there any transactions for the next/previous months?" The answer will determine whether or not their links are disabled, as well as where to send the user.
Strictly speaking, putting their logic into the Transaction List model does not seem appropriate, as whether or not transactions exist outside the requested range is beyond the concern of the Transaction List Model.
I guess I could also make another Model that would correspond to all Year-Month combinations where transactions exist. I could then pass this Model and the Transaction List on to the proper View.
Or should I deviate from the no-database-access-outside-the-model paradigm, and just throw some quick DB querying into the View (since the result is essentially a UI concern, making navigation easier)?
What do you guys think about this conceptual issue?
BTW, I am not using any framework. This is pet project designed to get me more familiar with the nuts and bolts of the MVC pattern.
... should I deviate from the no-database-access-outside-the-model paradigm, and just throw some quick DB querying into the View ...
The short answer is: no. If you're truly interested in learning MVC and better coding in general, taking shortcuts "just because" is a very bad idea. Domain logic separation is a fundamental concept of MVC, and to violate it would essentially be moving out of MVC into territory that is dominated by terrible code and "MVC Frameworks." If you want to learn "the nuts and bolts of MVC," you'll have to understand that the nuts and bolts are things like separation of concerns, and they are very important.
A lot of the text in your question suggest a few mixed ideas about what a model should be, so I'm going to redirect you to the most linked-to answer regarding MVC models. That answer encompasses everything you'll want to know about the concept of models. To summarize the most important concept from it, a model is not a class, it's a layer. The model layer has many components that all do their own thing, which leaves you with a testable, extensible, semantic, and logical domain logic layer.
Just remember to be careful: There is way more mis-information out there about MVC than there is reliable information. The worst thing you can do to learn proper MVC is look inside of a framework that claims to be MVC.
edit: I assumed the language was PHP while responding, so some of my answer might reflect that assumption. However the concepts are applicable across nearly all languages
The application is a financial tracking application. I'm stuck at the first page, which is just a list of the bank account transactions for the month. The transaction list is my Model. The Controller and View are easy enough to envision at this point.
Everything on your web page, is categorised in the View domain. A "list" is a visual object.
For a web application/page, The model exists on your server, within your database. Everything that exists on the web page, (Buttons, Forms, List boxes etc) is you View domain.
From most of what I've read, to the largest extent possible database access should be encapsulated in models, with little to no database access in Controllers and Views.
The View objects traditionally talk directly to your Model objects. Which means you have to provide a way for your View objects to talk to your database.
An example,
http//server/transactions (Get all transactions)
http//server/transactions?from=x (Get transactions from x)
http//server/transactions?from=x&to=y (Get transactions from x to y)
Could be your interface to your Model by your View.

MVC Design - How many controllers?

Overview
I’m building a simple web application consisting of a canvas and elements on the canvas.
The canvas supports the following operations: load, save
The elements support the following operations: move, resize
JavaScript on the web page sends a message to the server for each operation and the server sends an appropriate response.
My design
Note: the arrow between the Canvas and Element objects is supposed to denote that the Canvas object contains a list of Element objects. I didn't have the right symbols for the diagram.
Example work flow
An element on the canvas is moved generating an element_moved message.
The front controller manages the session and passes the message to the canvas controller with the correct canvas object.
The canvas controller inspects the message and sees that it is for an element on the canvas and passes it on to the element controller.
The element controller parses the message and updates the appropriate element object directly.
Question
Is this hierarchical arrangement of controllers common place in MVC designs or am I completely missing the point? I've searched for several hours but haven't found any sites which discuss MVC design in more depth than simply returning a page view.
My motivation behind the design was that each object that the client needs to interact with has a controller so that if the interface changes (to support new methods) then the corresponding controller can be updated without impacting the other parts of the design.
usually you won't have one controller calling another in MVC. What you have specified as Element Controller is really just a part of business logic to update the canvas model. If your use case requires you to update the elements independently of the Canvas, then you will have a separate Element Controller, calling the business logic to update the element.
Cheers,
Ryan
Your situation raises fundamental questions when attempting to organize concerns in client-side JavaScript for MVC.
First Fundamental Question
1) Should the entire "page" use one monolithic Controller, where member methods of such a Controller are the event handlers / starting points for working with a single Model and a single View for the entire page?
In regular expression speak ...
Controller{1}
Model{1}
View{1}
Since there is only ever one Controller, there is no ambiguity in the idea that its methods must serve as the event handlers / listeners for input into the scheme: Controller.moveCircle().
Playing dumb for a minute, if there is only ever one Model, then you can simply go to one place to create all the data / state handling methods that you need. Right? (hehehe) ;-) Model.calculatePosition(), Model.calculatePrice()
In the most basic client-side / web scenario, if there is only ever one View, one might think just putting all presentation logic there could get the job done: View.repositionCircle(x, y), View.repositionTriangle(x, y)
Discussion 1
Why might a monolithic Controller, Model, or View scheme like this be problematic in the future?
Can I transfer individual screen elements and their behaviors to other "pages" without any hassle or extra baggage?
Coupling and Cohesion
Think coupling. Does a monolithic Controller loosely or tightly couple accessing screen targets?
Think cohesion. Does a monolithic Controller group behaviors / methods related to accessing an individual target strongly or weakly?
Would Controller.moveCircleUp() and Controller.moveTriangleUp() be dealing with accessing one screen target, or two?
In this case, broad questions like these about a monolithic Controller would also apply to monolithic models and views. A Model is most likely composed of several objects for doing and dealing with the data / state of various things, so there's generally less confusion about it's place.
Yet, if it is a monolith too, then it must deal with the data / state of all screen targets. Even with using multiple object properties and multiple methods in such a model, that could get messy.
Re-usability and Maintainability
What I have written about here cannot be good for code re-usability and maintainability. Even if you are no SOLID expert, it is easy to understand why monoliths tend to violate the Single Responsibility Principle. You should not be in the same place to change something about a circle, where you also make changes for a triangle.
Why? Think of it this way. You are floating in the ocean after your boat capsizes. It is you and another crewman. Would you rather be joined at the hip, so that if he loses consciousness, he or she takes you down too? No, you would want to be independent of the crewman so that you are free to sink or swim on your own.
If you are coupled at the hip, you might hit each other in the face or make some other error that would not have happened if each was a single floater.
In other words, it is better to operate independently and work together, than it is to be joined at the hip and try to accomplish the same things. It is not about when things go well. It is about when thing go wrongly, or when independence is preferable. For example, when one is able to grab a rope ladder dangling from a helicopter, but the other is getting gnawed on by a shark.
You want to be able to reuse application elements in different screens or applications altogether. This is why loose coupling and strong cohesion are fundamental to object-oriented programming, and programming generally.
(**Note: View does not mean HTML only, even if this is the most common end result. Other possibilities include SVG, XML, Canvas graphics, image formats ... anything that fits the circumstance.)
Second Fundamental Question
2) Should each crafted, actionable object / element / target on the screen have its own Controller, Model, and View?
In regular expression speak ...
Controller+ (one or more)
Model+ (one or more)
View+ (one or more)
Discussion 2
Do you want to use screen targets / elements on other pages / screens and bring their specific behaviors with them?
In the first scenario, there is a 1:1:1 relationship between Controller, Model, and View. They are monolithic. There is one screen / webpage. In that setup, you cannot take a circle and put it on another page / screen without bringing along the logic for triangle, too!
If the goal is to make code reusable in another context, then the answer is that each shape requires a self-contained MVC arrangement. Each target would have its own Controller, Model, and View.
In effect, this would mean each screen element that you designate worthy would know how to accept input from an event, process it, and show the output. Some how, we made it back to something that sounds rather fundamental.
Final Thoughts
If one accepts the the above as true, then shapes are, well, alive. :-) They are independent of the context. Manipulating them should not depend on the some all encompassing, JavaScript, FrontController, event handling overlord to be triggered first, only to delegate the work to a method of the target's individual Controller.
PHP MVC
Server-side PHP uses the FrontController scheme before getting to the desired Controller sub-class because if you have a single point of entry into the application (/index.php), you have to translate (route) the HTTP request (/contact/send) into an instance of a Controller, and call the desired method from that controller: ContactController->send().
Performance
The real issue here is how well will the application perform after having downloaded and loaded all of the JavaScript into a user-agent.
Answer? The more you have going on, the more memory you will use. If each screen element has a minimum of three (3) files for its Controller, Model, and View, then ten elements could mean thirty (files to download) at minimum.
Of course, other configurations are possible, but that is where a tool of some sort might come into handy to concatenate and minify everything. In JavaScript, I would rather develop one object per file.
I hope this helps!

How can you rotate banner ads using CouchApp & CouchDB?

For context: this is an HTML app, with little or no browser side JavaScript. I can't easily change that so need to do this on the server.
CouchDB is built to not have side effects. This is fair enough. But there seems to be no method that i can conceive of with shows, views, lists to change what is shown to a user with subsequent requests, or based on user objects, without writing data.
And can a get request for document result in the creation of a new record? Im guessing not as that would be a side effect.
But if you can, you could just create a log and then have a view that picks an advert firm a set of documents describing adverts which is affected by the change in the log when a previous ad was shown.
I'm not actually going to show adverts on my site, I'm going to have tips, and article summaries and minor features that vary from page load to page load.
Any suggestions appreciated.
I've wrapped my head around how to work with the grain for the rest of the functionality I need, but this bit seems contrary to the way couchdb works.
I think you're going to need a list function that receives a set of documents from the view and then chooses only one to return, either at random or some other method. However, because you're inside a list function you gain access to the user's request details, including cookies (which you can also set, btw.) That sounds more like what you want.
In addition, you could specify different Views for the list function to use at query-time. This means you could, say, have only random articles show up on the homepage, but any type of content show up on all others.
Note: You can't get access to the request in a map/reduce function and you'll run into problems if you do something like Math.random() inside a map function.
So a list function is the way to go.
http://guide.couchdb.org/draft/transforming.html
Look into the various methods of selecting a random document from a view. That should enable you to choose a random document (presumably representing an ad, tip, etc.) to display.

MVC for desktop app with no data layer

Question might be tricky (because of its nature or my way of describing it), so really read this before answering.
I have this app to write:
a) desktop app;
b) no data layer in sense of database, files or any other repository (no need to save, store or load data);
c) app will have some computation algorithms implemented (Genetic Algorithm);
b) provides GUI which will display controls for app and computations results.
I am thinking about using MVC pattern but I have doubts how to use it. Since I have no data layer in sense of (for example) database (data is generated during execution based on user input) I am concerned about way of using MVC in this implementation. So far I have came up with two approaches:
GUI is the View. GeneticAlgorithm is the Controller. GeneticAlgorithmResults is the Model (as class that only stores data). Basic flow:
The View sends user input to the Controller;
The Controller is processing user input and generates data;
The Controller sends generated data to the Model;
The Model notifies the View about new data;
The View pulls new Data and updates the display.
GUI is the View. AppEngine is the Controller. GeneticAlgorithm nad GeneticAlgorithmResults are the Model. Now we have:
The View sends user input to the Controller;
The Controller is processing user input and sends control signals to the Model.
The Model updates its internal state (generates new data);
The Model notifies the Controller about new data;
The Controller pulls data to model;
The Controller processes data;
The controller pushes processed data to the View;
The View updates the display.
First approach seems to be more straightforward and more like MVC. The problem is that some logic would have to be in the Model - decide when to notify the model as not all data updates will be displayed, or maybe display will be updated with the sets of data not every little change. Those decisions will be based on user input. Whats more some additional processing of the data may be needed before actual display. This would be in the View.
On the other hand second approach seems to be more complicated and looks like to much messages are being passed to achieve the task. But it gives full control of Logic to the Controller and separates responsibilities of the View, the Controller and the Model (which is the main purpose of MVC).
Which approach would you recommend? Or maybe I should mix them and use first approach architecture with communication flow from second approach? Or some different design?
From my understanding of MVC, the second version is more like the strict MVC paradigm. However, one of my very intelligent teachers once told me that the design patterns are there to give a loose set of guidelines and are not necessarily meant to be followed to the T.
In my opinion, a mix of both is a good idea. If some logic ends up in the Model, it isn't the end of the world, it just means that you have to be more careful about keeping track of the separation of your components. If a small modification to MVC makes your life 50% easier (less message overhead), then it is probably a good idea.
I would definitely go with something closer to the second implementation. Yes, it does seem like more messages passed back and forth, but if your application grows and changes, you will be happy that you've built the application with small classes.
Consider: Where is the logic to handle mundane tasks like switching between algorithms, executing them and processing the data for viewing?
Genetic algorithms operate on some kind of input or starting data, don't they? You would get this from your data access layer. Don't you need seed data or initialization conditions? What about saving your results to file and retrieving them for review later? I would think that you need to do this once your application matures. Expect that at first you will use file based persistence. If you're feeling up to it, later you can upgrade to a database. If you code against an abstracted data persistence layer, you won't have to change business logic later to support the change from file to database.
You should use the strategy pattern to implement your algorithms. This will allow you to change the implementation of your solver from genetic algorithm to your other algorithms without having to change the business logic for each algorithm.
The business layer will see a ISolver that takes inputs, and you will call mySolver.Solve(). You should be able to switch between the different versions without having to change your business layer logic (Open Closed Principle). The only difference in the way the business logic should interact with the algorithms should be in the constructor, and even there, you should consider using a Factory pattern.

Resources