iOS: Handling of data - ios

Explanation
My app basically uses a mapview with an overlay of polygons that represent buildings, coupled with an annotation. So for this it imports a custom class called Annotation that handles the popup details when the annotation is tapped, meaning it store the building's name and address. At this time the callout (the blue disclosure button) loads an empty DetailViewController object (as there's not really any data to pass through).
I soon added a new feature in the form of a searchable table that loads custom objects of the Building class (with similar properties to Annotation, plus images and more details) that then loads in the aforementioned DetailViewController class with the building's details.
So to summarise, the MapVC contains multiple annotations, which when the relevant disclosure button is tapped open the DetailVC. SearchVC is accessed by a button on the MapVC and has a table of Building objects, which loads a DetailVC with the relevant data, like so:
Next Step
So now I want to implement functionality into the blue disclosure button on the callout, so when the user taps it it'll load the building details. At the moment all it has is the annotation's details. I could add the extra properties to the annotation to make it complete but I think it's much better to just work with one custom class called Building, which has a MKAnnotation nature. Then this Building class is loaded for the annotations and searchVC's table.
Question
So finally, what's the best way to go around this? I want all the data to be stored independently of any of the VCs in the diagram. I followed a tutorial from Apple (the BirdSighting one) which uses a separate Datacontroller class, which I'd then load into other classes. Is this the best approach?

You're talking about MVC, model-view-controller. This is a very smart way to handle things, and is a good practice to get into. The model stores the data, in this case, building names, etc. The view displays data. The controller is what connects the view to the model, updates the view, gets notifications from users and in turn updates the model.
I use a singleton pattern for model data. Only one instance of a singleton is ever present in an application. That way, the data is not bound to any one particular view controller. Data only gets updated in once place, the model. It's a lot easier to trouble shoot issues with a singular point of convergence for application data objects.
I have a macro that I define in my PCH file.
#import "DataController.h"
#define DATA() [DataController sharedInstance]
In my code I can easily get to my model class by calling
DataController *data = DATA();
All of my views and viewcontrollers access objects stored in DataController, so there are never two view controllers handling separate pieces of information independently. All references point to the same place.
Some people use the AppDelegate object to store data, but it can quickly turn into a 1000 line beast. I prefer to keep the AppDelegate clean :-)

Related

What's the best way to load data for a ViewController before navigating to it?

In my application there are two view controllers that navigate to a DetailsViewController.
Right now, when the DetailsViewController appears, I fetch data from the server and display it on the UI. I dislike this because the UI is blank while the network request is going on. What I want is that the data be loaded in the previous view controllers and then passed to DetailsViewController.
Now the problem is that I have the exact same "load-data-and-then-push" code in two view controllers and I'm not sure what the most sensible way is to remove the repetition.
One idea is to have the two view controllers inherit from a common superclass which contains the loading/pushing method. I don't like this strategy because, supposing I have more ViewControllers like DetailsViewController down the line, I wouldn't like to write a loading superclass for each one.
Another idea would be to define a static method in the DetailsViewController which the two view controllers can invoke but this method contains UI related code (specifically, code to show an HUD Progressbar and a UIAlertView in case network fetch fails) which makes me uncomfortable.
I am very new to iOS and Objective-C so I might be missing something simple and obvious.
My favorite would be in this case to create a new class which handles the loading of the data (like http-request, etc.) and to create a delegate protocol for this class. This delegate callback might then be implemented in your two viewControllers which would then perform the push segue to your DetailsViewController when called. Delegation is a very nice and powerful feature, check out the documentation here: Delegation
Well, I'd better write it in the comments, but I have no reputation for that.
Imagine you are reading a json with several students information (name, year, etc.)
you can create a student object with the property that will be read and an object that will have a method that will run in the background that will be responsible for accessing your WS (JSON or whatever it is) and record this information to the student object. So if you have 10 students you will have an NSArray containing 10 students. This array is what you will for your next viewcontroller.
It is a lot of code, but you think examples easily.
If you use Storyboards you can use prepareForSegue: sender: to pass your data/model class to your DetailsViewController. If you use xib's you can do the same after instantiating the DetailsViewController and before pushing it.
If you need to load subsequent data from your server you should write a class that does this network stuff for you.
If DetailsViewController needs to load some additional data, you can use something like a loading view like Andy suggested. This is a widely used method.

iOS Container ViewController data flow

My objective is to show dealer locations in two different ways: a map and a tableview.
I have a container view controller (DealersViewController) which contains two child view controllers: DealersMapViewController and DealersListViewController. The user can switch between the VCs with a UISegmentedControl placed on the navigation bar. Tapping on a map annotation or a tableview cell will push a DealersDetailViewController.
The switching is already implemented (using code from Changing view controller when Segmented Control changes) and seems to work fine, as does the pushing of the detail.
What I would like to improve is the flow of data between container and children. The dealer locations are downloaded (JSON) from the internet in the parent and on completion an NSArray *locations property is set on both the map VC and the list VC. This array will contain dictionary objects created automatically by AFNetworking, each with location data (each location dictionary will have a title, subtitle, latitude, longitude to conform to MKAnnotation protocol, but also other things like image and description etc).
My question is: How can I be sure that the container VC and both child VCs 'agree' on how location data is structured? Theoretically, if someone wanted to develop another child view controller to add to my container that shows dealer locations in a collection view for example, how can he formally know how to expect data.
Apple says: "If the container needs the child to declare methods or properties, it should define a protocol to enforce this:". I could force the children to declare the locations property but the array could contain anything…
Maybe the parent could be a datasource for the children? I haven't tried this approach yet.
I am probably overcomplicating things but my objective is also to learn how to properly create reusable components and also practice using stuff like custom protocols / delegates and design patterns in general.
Thanks.
If I understand correctly, your issue is structuring data so that all of your controllers have the same understanding of it.
Probably the best way to go around it is to create a custom location class, and have the JSON deserialize into an instance of that class and then just pass it around as you see fit. There's quite a few ways how to go around deserializing, but JSON Model is a nice example of how to handle it automatically.
Tl;dr: convert your JSON dictionaries to custom classes and then pass them to your child view controllers, via properties or delegates, whichever you find more convenient.

newbie ios - where is the model in MVC?

I'm making an application that does calculations.
i have a bunch of views and view controllers.
the user clicks buttons to open up and close areas of the screen triggering animations. certain text fields are disabled when others are edited. when you click calculate a bunch of math is done, and results are animated to the screen.
the views.. are all that stuff we do with the xib file or storyboard
the controller is.. the view controller that we start with when we make an ios app.. we reference outlets and actions
3.. the model is ??? im assuming the math i perform should go in the model.. any computational stuff that isnt directly affecting the view. but where the hell is the model?! do i just create a general object and instantiate it inside the controller? In all the tutorials ive seen .. i just see people use view controllers and associated views.
The model is not something that comes standard like the rest of the things you mentioned. When building a single view application in Xcode it comes with a viewController and an appDelegate. As you noticed, the model is missing.
That is because you build your own model. A model is typically an object you instantiate in your view controller and then manipulate your data through its methods. The model will be a .h and .m file that you make to create an object that, through its methods, manipulates the data from the user input.
Because it is not good practice to have your view directly talking to your model, and vice versa, your viewController acts as a liaison. The view (buttons, labels) contains on screen data that the viewController can access. Once the viewController has access to this data, it sends that data to the model. As stated earlier, the model can be an object that you instantiate in your viewController. It does the thinking of your app and manipulates the data that your viewController sends it.
A good place to instantiate your model is in the viewDidLoad method. This ensures that when your app is ready, your model will be too.
- (void)viewDidLoad
{
[super viewDidLoad];
self.myModel = [[Model alloc] init];
}
And the reference to your model as an instance variable should be put in your private class extension at the top of your viewController's .m file.
#interface ViewController ()
#property (nonatomic) Model *myModel;
#end
As always the design is upto you. I would suggest creating a core data model with what ever model objects you require (This will generate the class files for you). Becoming familiar with core data early in your iOS learning is a great way to pick up best practices.
This should get you started. Doing it this way will also allow you to easily persist the programs state, is easy to maintain and extend.
Good luck with your iOS development.
Yes, you should create an NSObject subclass and put your calculations inside it.
Yes, your Controller should then create the Model object, and use it to coordinate the View.
The term "Model" just refers to the collection of classes that you use independently of the UI. A poorly designed app may not have a Model at all. A well designed app will keep its Controllers free from being cluttered with business logic by providing a suitable Model.
A rough guideline to keep your Model delineated from everything else is that your Model should never #import <UIKit/UIKit.h>.
Your math actually goes in your view controller. Unless you want to reuse the same functions for various other methods.
Your model would be anything you want to store to Core Data or some other persistent storage.
Basically Views talk to the UI, Models to the Database, and everything else to the controllers

Existing solutions to edit NSManagedObjects via a UITableView?

In my iOS app, there are various Core Data entities that represent things like Appointments, Notes and Contacts.
I'd like the user to be able to edit selected attributes of each entity via a UITableView. Similar to the iOS Calendar app, when you click 'Edit', you're presented with a UITableView with editable values for Start Time, End Time, etc.
It's occurred to me that there could be a large amount of code re-use going on here, so I'm now considering creating a generic class, ManagedObjectEditorViewController that takes a managed object, displays selected attribute values within a table view, formatted according to their type, and allows them to be edited.
I can think of several neat ways of doing this, but before I spend a long time on this, I'm wondering if there's already something out there to accomplish this task? It seems like such a frequently used approach that I can't believe there isn't already some open source code out there.
Anyone heard of, or used anything similar?
I am about to do the same thing. Just started and works so far. A table that represents an NSManagedObject (Detail to a master view controller, has aspects of a master view controller itself.).
The whole table represents one NSManagedOjbect. There are fields and other controls that correspond with the simple properties.
There are to-one references where the referenced object is just displayed but can be changed.
There are to-one references which are editable NSObjects itself where 1 and exactly 1 of them exists.
There are to-many references which can be added, deleted and edited. Pretty similar to the calendar app or the address book app. (from a functional point of view. It looks different though).
For that I establish a delegate between the table cells and the view controller. This is mainly because I try to stick on the MVC pattern.
E.G. the cell serves as delegate for UITextViews, UITextFields or as target for Buttons etc.
The (Detail-) View controller which owns the NSManagedObject and all related objects serves as my delegate for the cells. It provides methods similar to IBActions to the cells so that the cell can 1) inform about the event and 2) hand over a related view, if required (I need that to display some popups accordingly) and 3) the object itself e.g. the object that is to be deleted or a person-object for which the data is to be fetched from the address book etc.
The View controller can then does its very own duties which is invoking other view controllers (Send Mail, select from Address Book, present a popover with options for the user to choose from, ...).
I just built that up yesterday evening. (It is a free-time project of mine).
I am happy so far but the concept is not really proven yet :) .
What is your current favorite approach?

Trouble understanding viewControllers in iOS

I'm new to obj-c/iOS and I'm having trouble understanding conceptually at least viewControllers. I've read a lot of the Apple Doc's, I've even used viewControllers to some extent in xCode, but I still don't quite get what they are, or what are the best ways to use them.
I've been an AS3 dev for many years so my mind works in the context of MovieClips/Sprites and the Display list to get graphics on the screen.
Ok so from my understanding...
A viewController is a kind of class that handles graphics in some
fashion and then allows you to do something with them?? What is it in it's most basic sense?
You seem to add viewControllers to a Window class, which I guess is a bit like
adding a display Object to the Display list?
What is it that a viewController does for you in it's most basic sense?
Are there certain things you definitely can't do with them or shouldn't do
with them?
Do viewControllers need to be connected in some way to the rest of the iOS framework to function (apart from being added to a window).
How exactly do they use data? (I've read up on MVC, I understand that conceptually this is a slightly different question) as I understand it you don't hardcode data into a viewController, so how does a viewController access any static data?
Let's say I just wanted to throw an image up on the screen, exactly what part would the viewController play in that process? is it just something which handles only one small aspect of that process or is it the whole show and handles everything?
Does one viewController handle multiple images? is it like it's term, a "controller" for all the images presented on screen, or does it handle one image at a time?
What is a viewControllers connection to the image(s) it handles? it contains references to them?
I'm using the Sparrow framework which is helping but I would still like to be able to get my head around what viewControllers are so I know how to use them properly.
Ha, I apologise for the above I know it must look like I'm completely confused :) thanks for any advice.
Hope this helps you:
A viewController is a kind of class that handles graphics in some fashion and then allows you to do something with them??
It's the glue between a View (Xib File) and the Data (Could be
CoreData or whatever you're using in the backend). All the UI Elements
you are using in the View you normally define as properties in the
controller to get access to them.
What is it in it's most basic sense?
You seem to add viewControllers to a Window class, which I guess is a bit like adding a display Object to the Display list?
I don't really know AS3 so I cannot compare Display lists with ViewControllers. But basically ViewControllers are there to handle
different types of transitions between the views and accessing
(setting/reading) the data which is displayed in the view.
What is it that a viewController does for you in it's most basic sense?
Like I've written above. Most basic sense they interpret what the user
does on the view and depending on the action of the user changes the
model.
Are there certain things you definitely can't do with them or shouldn't do with them?
It is always hard to keep the border between model and controller.
They are pretty close to each other. So what I normally try is to
delocate all logic stuff (like calculations, database access and so
on) this does more belong into the model part. But of couse you're
using these external classes in the controller.
Do viewControllers need to be connected in some way to the rest of the iOS framework to function (apart from being added to a window).
Well like you already have written the ViewController needs to be
connected to a view. Otherwise it would not make much sense. There are
different subtypes of UIViewController such as UINavigationController
where you probably need to overwrite some other methods to provide the
whole functionality wanted by these special subtypes.
How exactly do they use data? (I've read up on MVC, I understand that conceptually this is a slightly different question) as I understand it you don't hardcode data into a viewController, so how does a viewController access any static data?
There could be different approaches to store the data. Simplest way
would be to have the data directly stored in the UIViewController.
This could be a custom class which is the container of the data. All
changes are directly written into this class and displayed by the
UIViewController. But in most of the cases it makes sense to use
CoreData (Which is responsible for reading/writing the data into a
sqlite database). You could look at CoreData as your model and the
UIViewController gets the data from there and passes the data which
the UIViewController has received from the View back to it.
Let's say I just wanted to throw an image up on the screen, exactly what part would the viewController play in that process? is it just something which handles only one small aspect of that process or is it the whole show and handles everything?
The UIViewController would store an internal Property (UIImageView *)
which is in the Interface Builder connected with the UIImageView you
have created in the Xib file. So over these property you can change
through your Controller the image.
Does one viewController handle multiple images? is it like it's term, a "controller" for all the images presented on screen, or does it handle one image at a time?
Yes, this isn't a big problem. You can have as many images you want.
You just need to have the properties defined in the UIViewController
and linked to the View.
What is a viewControllers connection to the image(s) it handles? it contains references to them?
Yeah, its like a reference to the UIElement. You can then change
whatever property of the UIImageView you want directly from the
UIViewController
Some useful links:
Apple Official ViewController Guide
Apple Official ViewController Basics
You should have a look at Storyboards (U can use them since IOS 5.0)
I recommend you to check:
https://stackoverflow.com/questions/1939/how-to-articles-for-iphone-development-and-objective-c
Here are the answers to your questions:
No, it's doesn't handle graphics. It's the controller of the MVC design pattern. It handles the lifecycle of it's contents (for instance the views) and the data linked with.
A UIViewController is set as a root of an UIWindow. For instance, a UINavigationController is a subclass of UIViewController that stacks UIViewController in order to deal with the navigation.
Response in (1)
Try to be more specific with this question please.
As already commented, it's useful if you use the already built-in components like UINavigationController or UITabBarController.
For instance, you can have the data in instance variables and the display them in the contained UIView.
The UIView attached to your UIViewController will contain an UIImageView. Your UIViewController would have a connection with it in order to whatever changes you need, for instance, changing the image when the user press a button.
It can contain multiple UIViewsand therefore multiple UIImageViews (it's a subclass of UIView)
As commented, they would be contained on an UIImageView and would be linked programmatically or with an IBOutlet.
In a nutshell, a view controller is the controller in the MVC pattern. Please check this link before reading further so you're up to date with this pattern:
http://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html
OK, basically a controller manages a collection of views. It also fetches data from your model and sets the state of the views. It's important to note that the views know nothing of your model (your data), and the model knows nothing about your views. A controller also receives events from the views and decides how to change your model accordingly. It is essentially managing the synchronisation between your views and model.
There are technologies that help automate this such as KVO and key value binding. A google search will help you there.
One more thing. No other part of your application should access your views except for the controller. So generally in an application controllers tend to communicate with each other, for example via transitions or the delegate patterns between controllers under a navigation controller. So your application backbone tends to be controllers talking to each other.

Resources