Does Xcode force MVC design pattern by default? - ios

I'm new to iOs development and want to follow the correct design pattern, but it looks like Xcode forces the user of MVC design pattern by default.
I have the model (MyApp.h)
You have a view (where I can drag & drop components)
And I have a controller (MyApp.m)
Is this the correct way of thinking?
Thanks

I'll go with a very basic example.
You want to display a list of people, with their name, age and location, like this :
Bob 32 United States
Paul 22 England
Jack 24 France
...
Here, you will create a new class, inheriting from NSObject, which you will call Person. Your class will consist of a header file (.h) and implementation file (.m). It will have properties, to hold the different elements of your "real" person, and methods to access and/or work on them (get the name, increment the age, change the location). This is your model.
Then, you will use a subclass of UITableViewController, called CustomTableViewController, to present the data. This is your controller.
The view is in fact the tableView contained in your UITableViewController.
The basics behind the MVC pattern is that your CustomTableViewController is responsible for the communication between the tableView and your Person objects. And this happens in the implementation of your tableViewController, the file CustomTableViewController.m.
Your tableViewController will (for example) create an array of Person objects, get all the data from somewhere, create the Persons, store them into the array, etc.
Then, UITableViewControllers (and their subclasses, of course), implement a delegate method called cellForRowAtIndexPath:, which the tableView calls when it needs to display a cell. The tableViewController creates a cell, populates it with the data, and hands the cell to the tableView. This is how you handle the communication. You don't ask directly to your tableView to go get the data.
This also works backwards. If your tableView allows editing, it will inform the tableViewController of the user interactions, and it's the role of the latter to reflect the modifications on your model.

Not quite. It would be good to read about it from Apple's documentation:
Start with: this
and then you can go deeper into it here

Xcode doesn't "force MVC". It's best practice and Apple makes it easy to do, but one of the key concepts in MVC is the separation of the model object from the view and view controller objects, but this proper isolation is achieved solely through programmer discipline, not through the tool.
Regardless, I'd suggest you refer to Apple's primer on Model-View-Controller in the Cocoa Core Competencies guide. There are lots of good links on that page.

Related

Updating Struct instance

I'm Use structures by default when possible,
what's the best practice to update the original struct instance a copy of it was passed to another variable.
let's say I have a Post struct
struct Post {
let title: String
let likes: Int
let viewsCount:Int
var comments:[Comment]
}
and we have a simple Master-Details Screens
when pushing the details screen we are copying the post to the details scene, and there the data may be changed as likes increments, added comments and so on,
so when pop This ViewController, to the new data model to update the original model in the Master ViewController.
what are the possible solution and the best practices for it?
assuming we are using MVC or MVP
You could create a common shared model class that is responsible for holding the Post data and that both view controllers could use and observe.
This really has nothing to do with structs; it is simply the usual issue of passing data into a view controller on creation and passing data back from that view controller on destruction. It happens that in your case you are positing that this is the "same" data — i.e. you pass a Post to the detail view controller and you pass a Post back from the detail view controller — but that is just a contingent fact.
So, to answer the question as formulated, you would use any of the usual techniques. The detail view controller would need to pass the modified Post back to the master view controller. It could use a Notification or (more directly) you could use the standard protocol-and-delegate architecture.
On the other hand, if Post is the basis of your app's data, it would not be unreasonable to argue that the premise itself is flawed: this should have been a class all along, not a struct, exactly so that the data can be maintained in a central place and references to it can be maintained in different places.
Indeed, if things are more complex, you might have the app's data (including the Post) live in some third location off in model-data-space, and have all view controllers send a notification up to the data when they change it and have the data send a notification down to all view controllers in response (that is what Ralf Ebert's answer quite reasonably suggests). That sort of thing is a lot easier nowadays because (in iOS 13) we have observable objects and the Combine framework.
I would create helper functions and make them mutating. e.g.
mutating func incrementLikes() {
likes += 1
}
Make sure your properties are var.
Ideally classes are best for the role you described as object maintain identity.
Each post has an identity.
According to apple docs "use classes when you need to control the identity of the data you're modeling"
When you share a class instance across your app, changes you make to that instance are visible to every part of your code that holds a reference to that instance. Use classes when you need your instances to have this kind of identity.
Classes vs strut

iOS Best practice for handling model objects

There are different levels I'm asking this question at.
Case 1: Let's think about the typical drill-down design. Say a table view controller has an array of custom objects, and tapping a cell will push a view controller that allows the user to modify the object represented by the cell. In this case, should the pushed view controller have the custom object as a property of its own, or use a data source/delegate protocol to edit the custom object but not own it.
Case 2: A similar but slightly different situation is this. I'm using a singleton store to handle an array of bank accounts in my app. A view controller will show a list of the accounts, and I'm wondering if I should have the array of accounts as a property in my view controller or get the array via the store. (The array of accounts is accessed quite often.) I guess the only difference is a single object vs. an array of objects. I'm curious about how heavy these arrays can be, so whether it's faster to load the array from the store each time or have it as a property in the view controller.
Case 3: When should the local file system be used? In my app's example, bank accounts are accessed quite often, so I have them unarchived and set as properties upon launching the app, but for much bigger data, I only load them from the file system when they should be displayed or edited. I'm still not sure what the right way is.

From what place a databse should be accessed according to MVC

I have a problem to understand how to properly download data from a database to my model object according to MVC architecture in my app.
Here is how the app looks like:
/ NavigationController -> ViewController -> ...
TabBarController - NavigationController -> ViewController -> ...
\ NavigationController -> ViewController -> ...
So TabBarController is initial controller with 3 tabs. Under each tab there is a chain of UIViewController embedded in a NavigationController. Each View controlled by particular UIViewController is displaying data from database. These data are updated quite often so I need to download them from database periodically.
Then I have a model object. In my app I have only this one model object so all UIViewController have access to the same model object (I know each UIViewController should have its own model object but I have reasons to do that in this way).
As I understand MVC, the communication should be like this:
when a View must be updated, UIViewController sends a request for data to a model object
model object gets the data from a source
when the data are updated, model object sends information to a UIViewController
UIViewController updates data from a model object to a View
This should be OK. But I am not sure where should be placed a DatabaseController which connects to a database and sends requests to it. This should be separated controller and model object must have a reference to it because he needs to tell him that he needs update its data.
I have found some blog with information that the DatabaseController should be created inside the model object and separated from model object code using a category. My opinion is that this is bad idea because it breakes MVC architecture.
What do you think? What is the best solution for placing DatabaseController in the app? Should I put it into the object model or outside...
I've never used Objective-C before, but in general OOP, the code to access the DB should definitely be placed in a single, separate place - among other things, this makes it mush easier to maintain and modify the code to access the DB in the future, and makes code clearer in general.
A well-known and widely used approach is the Data Access Object (DAO) pattern, which allows you to abstract the persistence details of your application from the rest of the logic.
The Repository pattern is also used very often for this purpose.
In your case, if you have a model class called Thing, you'd create a ThingDAO, with methods such as getAllThings(), getThingById(id), updateThing(thing), deleteThing(id), etc.
Then you can call this object from your Controller, or better in my opinion, from your model class(es).
You may think that, as we add another layer, "it breakes MVC architecture" - in my opinion, actually the DAO layer is a part of the model. I think your concept of model is probably not quite right - bear in mind that the model is not one class, but a group of (potentially thousands of) classes. In a big app, your model would contain things like Entities, DAOs, EventListeners, Handlers, Managers, Commands, Transformers, Helpers, and many other things...
Data access, and more, like business logic should be part of the model, and I'll try to explain why:
putting more and more of the application logic into the model component leads to the fat models, skinny controllers paradigm
fat model, skinny paradigm leads to unit-testable code, as controllers are not very suitable for unit testing
this approach also increases the reusability of your components, as it's unlikely you'll reuse controllers (most of the controllers are application-targeted)
Of course this applies to MVC, however as this pattern is heavily used in the iOS development, it makes sense to primary focus on it.
My suggestion would be to move towards MVOC architecture where O represents Others. Others would be a layer that does not fit in either of M, V, or C. Here O would be your network layer. A singleton object that your controller calls to fetch data and gets a filled model object in return.

Core Data create super entity automatically? Where and when?

I have the following datamodel to manage measurements (heart rate and skin response)
When I'm acquiring a new measurement it's going to be an entity of "MinuteStress"
Now I want to programmatically check if a corresponding day and month entity exist and if not create one automatically and add my measurement to their average.
My first question would be: Where is the right place to check for the super entities? Is it a good idea to do this in the NSManagedObjectSubclass of "MinuteStress" or is it better to do so after I create the entity in my viewcontroller?
My second question would be if there is a smart way to create super entities from a sub entity?
In theory you can do that in the awakeFromInsert method of your NSManagedObject subclass, but that's a Bad Idea (tm) because you can trigger other Core Data events... see the "special considerations" section under awakeFromInsert in the Apple Docs for more info.
You'd be better off to query for the superclasses in the view controller and create them if needed, then create the MinuteStress instance.
You might also want to write some convenience methods for creating related child objects (like -(DayStress *) createDayStress] on MonthStress for example) where you create a child object and automatically set its parent reference (and any initialization values) before returning it. It makes the code flow in the view controller much nicer IMO.

Scope of viewmodels in asp.net MVC 3

I have read online that it is bad practice to use a "kitchen sink" model:
Rule #3 – The View dictates the design of the ViewModel. Only what is
required to render a View is passed in with the ViewModel.
If a Customer object has fifty properties, but one component only
shows their name, then we create a custom ViewModel type with only
those two properties.
Jimmy Bogard's subsequent explanation of how this is good, however, left me a little questioning. It'd be so easy to have my Model just contain a list of Customers, I could even use my POCO's.
So now I get to create custom little view model fragments for every page on the site? Every page that uses a Customer property would get one, but of course could not be shared since some of the information is extraneous, if one page used Age but not Name, for example. Two new mini view model classes right?
This is very time consuming, and seems like it'll lead to a million little custom view models - can someone elaborate as to the utility of this approach and why the easier approach is bad?
View model class can be used not only to transfer values, but it also defines data types (data annotations), validation rules and relations different then ones used in model. Some advantages that come to my mind right now:
There are different validation rules when you change user's password,
change his basic data or his subscription setting. It can be
complicated to define all these rules in one model class. It looks
much better and cleaner when different view models are used.
Using view model can also give you performance advantages. If you
want to display user list, you can define view model with id and name
only and use index to retrieve it from database. If you retrieved
whole objects and pass it to view, you transfer more data from
database than you need to.
You can define display, and editor templates for view models and reuse them on different pages using html helpers. It looks much worse, when you define templates for model POCOs.
If you would use your POCO objects as view models, you would essentially be showing your private objects and break the encapsulation. This in turn would make your model hard to change without altering the corresponding views.
Your data objects may contain details that are appropriate only to the data access layer. If you expose those things to the view, someone might alter those values that you did not expect to be altered and cause bugs.
Many of the same reasons as for having private members in OO languages apply to this reasoning. That being said, it's still very often broken because it's a lot of extra work to create all these "throw-away" models that only gets used once. There exists frameworks for creating these sorts of models, though the name eludes me, that can tie objects together and pick out the interesting properties only which takes away some of the drudgery from creating specific view models.
Your View Model tells the View how data should be shown. It expresses the model. I don't think its necessary to have two view models unless you have two ways to express your model. Just because you have two pages, doesn't mean you will be showing the data any different way, so I wouldn't waste time making two mini View Models when it can be in one reusable view model, Imagine if later you have a page that needs Name and Age, you would create another view model? It's absolutely silly. However, if you had two pages both showing 'Age' and it needed to be shown in a different way, then I would create another one.

Resources