How to structure my code - ios

I have a UIPageViewController that contains two "pages" of UITableViewControllers. These UITableViewControllers need to be filled with JSON data from the internet. However, this UIPageViewController needs to be reused in many places within my app meaning that the data that the UITableViewControllers use changes.
My question is: how should I structure my code so that I can easily change the data that the UITableViewControllers access? Should I pass the data to the initialised UIPageViewController so that it can pass it on to the UITableViewControllers, or is there a better way to do this?
Thank you!

This is quite a broad question, and there are potentially many different approaches. Which one is best is arguable and not really inferable from the information available.
If you have UITableViewControllers that are simply displaying downloaded JSON data, then you might want to have a dedicated class that deals simply with downloading the data. E.g. MyJSONDownloader.
This class might have a method like - (NSArray *)getLatestData that returns the latest things you want to display in a table.
Then in your UITableViewController subclasses you want to call this method and display the data accordingly.
I'm assuming from your statement:
These UITableViewControllers need to be filled with JSON data from the internet. However, this UIPageViewController needs to be reused in many places within my app meaning that the data that the UITableViewControllers use changes.
that you will be downloading data frequently from the web and that this data is constantly changing. (If not then change your question.)

Related

Best way to simplify/refactor tableView code setup in objective-c

Every single time I need to create a simply tableview that is populated by a simple data set retrieved from my web server which has its code executed like this: SELECT * FROM table I find myself spending two blady whole hours trying to get the new view controller up and running as I try to update some variable names, copy and paste the required code from my previous view controllers. etc its ridiculous.
This is the end result for all my view controller pages where each will contain different data sets depending on the web service urlĀ being called:
Here is a link:
Link to downloading staple code .h .m and .xib files
This view controller contains a few simple elements seen throughout all data viewing pages:
UITableView
Titled header views
table indices.
refresh table control feature
data connection retrieval code
data connection succeeded
data connection failed
setting up all my bloody delegate and data source methods.
I find myself having to copy and paste all the staple code, functions, variables, properties, and IBOutlets; and to be frank, its getting ridiculously paintaking to have to repeat the same procedure over and over again but changing variable names between the different view controllers.
This is why I believe people create simple component like structures that make it easy for users to get tables setup and up and running.
How can I reduce this big chunk of code:
to something that will allow me at most do this:
Create a new view controller
Setup xib file
create appropriate IBOutlets, and hook them up to the xib.
Here's where it needs to change
I need to now simply able to write something like this the next time I am goin to create another data viewing View Controller:
[self setupTableForDataSetType:]; //This will make sure the tableView knows which data set its dealing with and so therefor know which DataModel classes to use
[self retrieveDataWithWebServerURL:]; //of course so that the connection code can make the right server connection with the URL given for the data set required.
Thats it. So that it is super easy for me to create the tableView pages desired and show the results quickly! Atm I have the same code everywhere in different view controllers.
Whats the best way to go about doing this?
Create a viewcontroller with all your customizable values as properties and reuse changing its values.
Well, subclassing is probably the best (maybe only) way. I've done something like this for tables with an index, since they're a bit of a pain to set up. I created a IndexedTableViewController that handles almost all the load. I make my app table view controller a subclass of that controller, and then I only need to feed a simple array of custom objects to the method, convertArray:usingSectionKey:secondarySortKey:(implemented in the IndexedTableViewController) which creates the sections and the index. The only other method I have to implement in my app table view controller is cellForRowAtIndexPath:(though I would have to implement more, especially didSelectRowAtIndexPath:, if I were doing more things with this table).
Your needs sound a bit more ambitious than this, so it would take quite a bit of work to make a superclass that would be general enough to work with most of your apps. A method like setupTableForDataSetType: could be quite complicated if it needs to handle many different data types.

Should I use Core Data or NSCoding to preserve a table view controller's data?

This is a pretty basic question, but I have searched all over for an answer that caters to my situation and found little.
I'm using ECSlidingviewController to make a left drawer/menu control like Facebook, Pulse, and many others. (Actually quite surprised this isn't part of the Apple SDK)
When I select an option from my menu controller, it pops the current top controller off, and pushes the view controller selected by menu. My main view is a tableview of local places, and its quite expensive/time consuming to retrieve local spots from a server every time the view is loaded, so I'd like to save the last loaded collection object (My object that wraps a dictionary with simple accessor methods).
I've explored NSCoding/NSKeyed* and Core Data so far and NSCoding seems like a good plan, but I'm not sure if it would be suited to 30 entries of custom objects (each has 640x320 picture and a few strings). At the same time, using core data for a simple collection object seems like building a mansion for a closet. I've also considered trying to keep the view controller around in memory, but that seems way too wasteful. Also, NSUserDefaults doesn't seem to fit the job either. Would the UIKit state preservation techniques work even when the app is in foreground? And finally- would NSURLCache be a good solution to saving the tableview data?
All I want is a quick and standardized way to reload my tableview's last data source without any network requests, or 100 lines of code.
I'd use Core Data and a fetched results controller. If you start off with a master detail template for this then the code is all generated for you. The main benefit is that the saving is transparent for you and memory management is also transparent (you just set the fetch request page size to a suitable value).
A solution using NSCoding will work, and for 30 results may well be faster. If you know you'll never have more than 30 then it could be attractive. But you need to code (and save) and decode yourself and you still have basically the same table data source code.

UITableViewController data source from coredata

I have found two ways of populating UITableView with data from coredata. One way is to use NSFetchedResultsController and implement the delegates for update controller:didChangeSection. Other way is to copy data from coredata to local array of Managed objects. Handle the updates on local array and saves the changes to managedcontex.
Both could be found on developer.apple.com.
I would like to hear pros and cons for each metod?
Thanks.
It is better to use NSFetchedResults controller, because your current view controller may not be the only one changing the data. It may happen in the background, or through some other view controller (for example, if you have a split view controller, you may be changing data related to a record in the master view controller, in the detail view controller). In those cases, you want your table to automatically reflect the changes. In extremely simple cases, where you are the only view controller in town, it may be easier the other way, but do it the right way and you will be happy.

Multiple TableViewControllers & Segues

I have a TableView that is populated with data. When a user taps a row, a new TableView opens with more data to choose from. This data changes based on the row the user taps. Much like an application where the user chooses from a list of car makes, and then models. Is it possible to handle a situation like that with a TableViewController for the car makes, and 1 TableViewController for the models? Or would there be 1 TableViewController for the makes, and then a separate TableViewController for each make's set of models? I don't know the best way to approach this :-( I'm making an app of my own which is very similar in structure and I can't seem to find any documentation on how to accomplish this. Thanks in advance.
No, your models controller would serve for all makes. It would be passed an ID of the make requested and then fetch the necessary data accordingly.
Something like this might be of some help:
http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/TableViewAndDataModel/TableViewAndDataModel.html
But I think the foundation of your problem is not necessarily to be found in a working example of your exact needs, but more in general tutorials for ios development.
Sorry if I have assumed you're just beginning ios development. I might be able to improve this answer if a more specific need is clarified (like how do I pass the ID to the model controller) etc
In general - this approach would utilize a separate UITableViewController for each data level and use a UINavigationController to handle the transitions between the different view controllers.
This process used to involve a lot of boilerplate code, but it is now aided by StoryBoards. You can setup each level in a storyboard and handle the transitions and setup data for the next view in performSegueWithIdentifier:.
You can see a tutorial here on using StoryBoards: http://kurrytran.blogspot.com/2011/10/ios-5-storyboard-uitableview-tutorial.html
You can see another Sample From Apple that demonstrates the data drill down with a Storyboard: http://developer.apple.com/library/ios/#samplecode/SimpleDrillDown/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007416-Intro-DontLinkElementID_2

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