UITableView vs UITableViewController - iphone

Can someone explain to me the advantages of a UITableViewController over a UITableView? Generally, I use the controller but the basic table view seems a lot more flexible.

I always use UITableView. I never use UITableViewController.
Using UITableViewController is confusing. Each controller is supposed to do one screen except container controllers.
Well, UITableViewController is a controller and most of the time, a tableView is simply not the only thing there.
If you look at documentation:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewController_Class/Reference/Reference.html
UITableViewController provide very little new interface compared to UITableView. None of which is essential.
– initWithStyle:
(duh? I initiate my tableView in nib and I customized a lot anyway)
Getting the Table View
tableView property
(the original tableView)
Configuring the Table Behavior
clearsSelectionOnViewWillAppear property
(okay, just put some code on ViewWillAppear)
Refreshing the Table View
refreshControl property
[tableView reload]?
So you see,
So unless you want your code to look neater (and not much more), there is no reason to use UITableViewController, that I know of.

I don't think you understand your own question.
The UITableViewController is a controller.
The UITableView is a view.
One isn't better than the other, they're completely different objects, used for completely different things.
I'd spend some time learning the Model-View-Controller pattern so prevalent throuought Cocoa and the iPhone SDK.
The Model-View-Controller Design Pattern

The idea is that ViewControllers hold a tree of subviews (and sub viewcontrollers) and manages dispatching events to/from its subviews. For example, you might have a view that holds an image, and that view lives in a view controller that handles orientation changes and memory warnings, etc.

This is one thing I find very confusing about Cocoa: Apple's implementation of MVC (or at least the terminology they use) is questionable. In Cocoa, most views are themselves actually acting in some capacity as controllers insofar as the MVC pattern defines them (just look at UITableView--most of its methods are actually controller methods). Therefore you have Apple's additional concept of a view controller on top of what is already to some extent a controller. The fact that you don't even need to use UITableViewController at all (even with data binding) basically proves that the view is acting as its own controller. In MVC, you can't have a view bound to a model without a controller (that's the whole point of the controller in MVC).
It appears to Apple's developers, that a "view controller" (e.g. UITableViewController) is really more of a slightly higher-level helper/manager class that manages the more low-level UITableView class and enables a few key additional capabilities that pertain more to how the table view interfaces with the general UI of the app.
Additionally, it appears that Apple intends for a view controller to actually be more of a screen controller, recommending only one view controller per screen (presumably meaning you can't nest view controllers). I maintain that calling this concept a view controller is a misnomer.
Please don't hesitate to correct me on this anyone, I'm still very new to Obj-C/Cocoa myself.

UITableView is a view and UITableViewController is a controller that has UITableView as its root view.
So, by using UITableViewController:
You have one root view that is UITableView itself. So it takes less memory than UITableView with a UIView as parent view in its controller.
It provides you with a ready-to-use template, if you needed a controller and a UITableView as its main display view.
Static table views are only valid when embedded in UITableViewController instances.

The link above returns a "Page Not Found." For some reason, even the corrected link returns a "Page Not Found" when hyperlinked (perhaps Apple doesn't allow linking into their developer site).
To find the relevant information, go to Apple's Developer Connection (http://developer.apple.com/index.html) and search on "cocoa model-view-controller design pattern".
In the table of results, select the "Cocoa Fundamentals Guide: Cocoa Design Patterns." On that page scroll down the Table of Contents on the left side until you see the item "The Model-View-Controller Design Pattern." Select that item to read more details about that particular design pattern.

Related

The best implementation of a tableview in Model View Controller

What is the best implementation of a tableview in Model View Controller?
I'm developing my app without storyboard, all programmatically .
Is it possible to implement a TableView in a UIView? I tried it, but If I implement the TableView in a view, when the controller recives a button action, I can't modify or access to the tableView of the View...
After that, I tried to implement the tableView in a ViewController and it works perfectly, but I don't know if this is a good implementation because I found the same problem when I wanted to implement a TextView/TextField with a Piker, for example.
My goal was to had a clean code of viewController with a views and controllers (of buttons etc) and now I find myself with a uiviewController with the view and multiples components when I wanted the components were in the corresponding views.
Thank you very much!
It is all possible, and the problems you are running into are not because of it being something that you should not do, but that it is something that inherently works slightly differently than before. To answer your question directly, I would implement the tableView as the modal view controller directly, either as a UITableViewController or a UIViewController that inherits the table views delegate and datasource (this method being chosen if you don't want the table view to use up the entirety of the modal view controller's space).
TableViews are simple to use, but understanding every detail of how they work will make you far stronger and able to use them in any of these scenarios. I am not going to write you a guide on their use, butcontinue studying them before you declare that anything "can not be done".
Knowing what classes to implement the delegate methods becomes very important during these different scenarios. It is often easiest to use textfields delegate's implementation in UITableViewCell's subclass rather than in the UIViewController they are in. This allows for a more modular creation.
I find that working with the storyboard allows for a much quicker learning curve, and also a time saver. The one excuse I will give you for working without a storyboard is if you have an extremely slow computer.

should uiviewcontrollers always be part of the viewcontroller hierarchy?

In the app represented by the image below, I'm currently using three UIViewControllers: One master view controller, one for the main menu, and one for a settings screen which is launched by the main menu. As I'm learning more about how UIViewController works and what it's designed for, I'm questioning the wisdom of my architecture.
It seems to me that the main point of subclassing is to be able to override the methods which get called automatically during the life cycle of the controller: viewDidAppear, viewWillAppear, willRotateToInterfaceOrientation, etc. It appears that these methods are only called if the UIViewController (or subclass) is part of the UIViewController hierarchy. Therefore, there's no point in subclassing UIViewController unless I'm going to use one of the standard means of creating a viewcontroller hierarchy i.e. UINavigationController, [UIViewController presentModalViewController] etc.
I'm wary of using the Cocoa-style means of adding view controllers to the hierarchy because they all seem to be very restrictive. For example, I could display my settings screen using [UIViewController presentModalViewController], but but I don't want it to obscure the entire screen. There's background animation which I want the user to be able to interact with even while the settings screen is visible.
Here are my questions:
1) Is it silly to subclass UIViewController unless I'm going to be adding it to the viewController hierarchy via one of Apple's techniques?
2) Am I correct in my assumption that the built-in means of displaying new views are too restrictive for me, and in order to have the flexibility I want, I'm going to need to just load views via [view addSubview]
3) If it's true that subclassing UIViewController makes no sense for my menu and settings views, how should I avoid having all of my code in one monster UIViewController subclass. Should I just subclass NSObject, add the appropriate IBOutlets and IBActions and pass that in as the File's Owner when I load the nib using [NSBundle loadNibNamed]?
Good question. First, a point of clarity: What you refer to as "one of Apple's techniques" is referred to in the UIViewController Programming Guide as "indirect presentation", and includes things like modal presentation, being pushed on a navigation stack, presenting a popover controller, etc. Basically all of these view controller methods are considered "indirect" presentation methods, while the use of -addSubview: (something like [someView addSubview:myViewController.view]) is considered "direct" presentation.
From said programming guide: (Giant Block Quote...)
It is recommended that you use only
the suggested techniques for
displaying the views of your view
controllers. In order to present and
manage views properly, the system
makes a note of each view (and its
associated view controller) that you
display directly or indirectly. It
uses this information later to report
view controller-related events to your
application. For example, when the
device orientation changes, a window
uses this information to identify the
frontmost view controller and notify
it of the change. If you incorporate a
view controller’s view into your
hierarchy by other means (by adding it
as a subview to some other view
perhaps), the system assumes you want
to manage the view yourself and does
not send messages to the associated
view controller object. (emphasis mine)
Apart from your setting up your
application’s initial interface, most
other views are presented indirectly
through their view controller objects.
All that is to say that you are correct in thinking that all of those UIViewController messages will be wasted if you if simply add the view to a view hierarchy directly, and take no other further action (key window being the exception). That quote also mentions that it is most common to use indirect presentation.
1) I hesitate to make a blanket statement and say "Yes, in all cases, it is silly to subclass UIViewController unless you're presenting it indirectly." I'm sure there is some good use for it somewhere. I'll settle for saying that I have personally never done so.
2) Absolutely, I would not use a UIViewController subclass here.
3) Allow me to direct your attention to another area of The Programming Guide:
In iPhone applications, the views in a
view hierarchy traditionally cover the
entire screen... If you want to divide
a view hierarchy into multiple
subareas and manage each one
separately, use generic controller
objects (custom objects descending
from NSObject) instead of view
controller objects to manage each
subarea. Then use a single view
controller object to manage the
generic controller objects.
That pretty clearly syncs up with what you're wanting to do here. You're dead on with your self suggested approach. That "Settings Screen launched by main menu" should be managed by a generic controller object descending from NSObject, which is in turn managed by your full-screen UIViewController subclass.

Must a view controller always have a delegate in iPhone apps?

I'm learning how to develop my own iPhone apps but I'm having a tough time understanding certain concepts.
First, am i right to say that for every view, there must be a view controller for it? And for every view controller, must there be a delegate for it?
Also, what is the role of mainWindow.nib? Most of the tutorials that i've read don't seem to touch that nib at all. What always happens is the setting up of a NavigationController as the root controller, which pushes another ViewController onto the stack and this ViewController will have another nib associated with it.
So can i assume that i can safely ignore the main window nib?
It's all about MVC (Model View Controller), innit?
The Model, well that's up to you - what does your app do? Think of it as the backend, the engine of your app, free of the cruft of font size decisions and touch events.
The View, Apple pretty much wrote that for you. You use their Textfields and tables and imageViews. You assemble them together using Interface Builder into your GUI (packaged as a .nib). You rarely, if ever need to subclass the standard view elements (in a game you want a custom View to draw to, as all your drawing is probably custom). You can break different parts of your GUI into different .nib files if this helps you manage them. It's entirely up to you.
The Controller, so you have probably got some work todo to enable your GUI to represent your model. You need Some Controllers. How many? However many is manageable by you. If you had a view containing 2 subviews would they each need a view controller? Nah, probably not. How complicated is your code to hook up the view to the model?
Some GUI patterns are so common that Apple even wrote the Controller code for you. EG the controller for a UINavigationBar, UINavigationController. So, if your app has hierarchical views that you need to navigate around and you need to display a navigation bar you can use an instance of UINavigationController instead of writing your own class. Yay!
Surely tho, the UINavigationController code (or any other viewController) can't magically know how to integrate with our model, with our view, can it? NO, it can't. In general in Cocoa if there is some class of object that mostly works off the shelf but also has optionally configurable behavoir - allowing us to tailor it to our needs - it is done by Delegation. ie Instead of subclassing UINavigationController we tell the specific instance of it where to find (for want of a better term) it's custom behavoir.
Why? Let's say you have a navigationController, a tableView and a textfield. UINavigationController mostly take care of your navigation needs but you have to have a crazy QUACK sound play each time the user moves to a new view. UITableView is mostly exactly everything you need from a table, EXCEPT you really want the third row in the table on the front page be twice the height of the other rows. And the standard, off -the-shelf UITextField pretty much takes care of your textfield needs EXCEPT you need your textfield to only be editable when the user is facing North. One way to handle this would be to create 3 new classes, a custom UINavigationController, a custom tableView and a custom textfield, and to use these instead. With delegation we could use the classes as they are and have one object be the delegate of all 3 instances - much cleaner.
Delegation is mostly optional, the docs will tell you when, and it's down to you and whether you need that custom behavoir.

When to use a UIView vs. a UIViewController on the iPhone?

I have always sort of wondered when to use a UIView vs. a UIViewController on the iPhone.
I understand that you shouldn't use a UIViewController unless it's a full-screen view, but what other guidelines are there?
For example, I want to build a modal overlay - a screen that will slide into place over the current screen. If this modal overlay is full-screen, should it be a UIViewController? The last time I built something like this, I subclassed UIViewController, but now I wonder if that was correct.
From Apple's View Controller Programming Guide for iOS:
"The most important role of a view controller is to manage a hierarchy of views. Every view controller has a single root view that encloses all of the view controller’s content. To that root view, you add the views you need to display your content."
Also:
"There are two types of view controllers:
Content view controllers manage a discrete piece of your app’s content and are the main type of view controller that you create.
Container view controllers collect information from other view controllers (known as child view controllers) and present it in a way that facilitates navigation or presents the content of those view controllers differently.
Most apps are a mixture of both types of view controllers."
This is a great question.
My basic rule of thumb. Is that every major 'page' of an application gets it's own view controller. What I mean by that is that during the wire framing stage of application design, everything that exists as its own entity will eventually be managed by its own View Controller. If there is a modal screen that slides over an existing screen, I will consider that to be a separate 'page' and give it its own view controller. If there is a view that overlays and existing page (such as a loading screen or help popup.) I would treat those differently, implement them as UIView subclasses and keep the logic in that 'pages' view controller. It the popup has behavior I will communicate back to that pages View Controller using the delegate pattern.
I hope this helps. It is very much a philosophical and architectural question and much could be written about it.
I use UIViewController whenever a view is full screen and either has outlets/actions and/or subviews.
Put everything on a screen into a UIViewController until the view controller starts to have too much code, then break out the screen into multiple UIViewControllers contained by one master view controller...
To put that into context of your answer, make a view controller for that modal overlay. It will have one anyway if you are using a nav controller to present it (and you probably should).
I have a somewhat different approach:
Override UIView if you plan to do custom drawing in drawRect. Otherwise, subclass UIViewController and use [self.view addSubview: blah] to add the components of the page.
There are a few other special cases, but that handles about 95% of the situations.
(You still will often need a UIViewController with a custom UIView. But it's common to have a custom UIViewController with no corresponding custom UIView.)
Is the thing that slides in a self contained screen? I mean, does it directly interact with the parent? If so, make it a UIView, if not, probably recommend a UIViewController.
A UIView is part of the UIViewController see the view property of UIViewController for this. As you pointed out correctly UIViewController manages a complete screen and there should be only one visible UIViewController at a time. But in most cases you will have more UIViews or subclasses of UIView visible on the screen.
The example you gave would be a correct use in most cases. As you may have noticed you will get a lot of functionality when subclassing the UIViewController. Animating the appearance and dismissal of the UIViewController would be one of them.
As marcc pointed out if the thing you want to slide in is not a self contained screen you would be better off using a UIView.
As a conclusion I would say that if you want to use the functionality that comes with subclassing UIViewController than go for it make it a UIViewController. Otherwise a UIView might be better.
The itunes U Standford class has a great lecture on UIViewControllers I would recommend watching it, because it has a lot of information regarding UIViewControllers in general.
If you are familiar with the MVC pattern, then you should be able to understand the difference between UIVIew and UIViewController. To make a simple statement, UIView is for rendering UI elements on screen. UIView is the superclass of pretty much all Cocoa Touch UI elements. Those elements do not know what information they are supposed to display, what they should do when a user clicks a button, what happens when an async network request is completed and so on. UIViewController is for all that and more. The view controller is responsible for placing the UI elements in the correct locations on screen, setting the contents of the UI elements, handling button presses and other user inputs, updating the model when needed etc.
Conceptually, a single UIViewController controls the contents of the whole screen in an iPhone App and that is why it is often easy to think of things in terms of view controllers. If you need a view where the user can select ingredients for a food recipe, you'll need a UIViewController for that. I made this distinction for myself because coming from a Java background I wasn't used to the framework enforcing MVC. I would think of things in terms of UIViews, and start implementing them that way and then run into all sorts of trouble because of that. If you are going to stick to UIKit for your App, then the workflow Apple has made for you is: for each separate view in your App, create a UIViewController subclass and then use Interface Builder to place the UI elements and to create connections for buttons etc. It works wonders, saves a ton of time and lets you concentrate on making your App function well.
I use UIViewController for showing View on full Screen.
For better control on custom view I prefer subclass of UIViewController instead of UIView, earlier I was using UIView for making custom sub class.

Why shouldn't a UITableViewController manage part of a window in Cocoa Touch?

I have a view that contains a UITableView and a UILabel which works perfectly as far as I can tell. I really don't want to manage the UIView and UITableView with the same controller as the UITableViewController handles a lot of housekeeping and according to the documentation:
If the view to be managed is a
composite view in which a table view
is one of multiple subviews, you must
use a custom subclass of
UIViewController to manage the table
view (and other views). Do not use a
UITableViewController object because
this controller class sizes the table
view to fill the screen between the
navigation bar and the tab bar (if
either are present).
Why does Apple warn against using it and what will happen if I ignore this warning?
Update: Originally I quoted the following from the Apple Documentation:
You should not use view
controllers to manage views that fill
only a part of their window—that is,
only part of the area defined by the
application content rectangle. If you
want to have an interface composed of
several smaller views, embed them all
in a single root view and manage that
view with your view controller.
While this issue is probably related to why UITableViewController was designed to be fullscreen, it isn't exactly the same issue.
The major practical reason to use only one view controller per screen is because that is the only way to manage navigation.
For example, suppose you have screen that has two separate view controllers and you load it with the navigation controller. Which of the two view controllers do you push and how do you load and reference the second one? (Not to mention the overhead of coordinating the two separate controllers simultaneously.)
I don't think using a single custom controller is a big of a hassle as you think.
Remember, there is no need for the TableviewDataSource and the TableViewDelegate to be in the actual controller. The Apple templates just do that for convenience. You can put the methods implementing both protocol in one class or separate them each into there own class. Then you simply link them up with the table in your custom controller. That way, all the custom controller has to do is manage the frame of tableview itself. All the configuration and data management will be in separate and self-contained objects. The custom control can easily message them if you need data from the other UI elements.
This kind of flexibility, customization and encapsulation is why the delegate design pattern is used in the first place. You can customize the heck out of anything without having to create one monster class that does everything. Instead, you just pop in a delegate module and go.
Edit01: Response to comment
If I understand your layout correctly, your problem is that the UITableViewController is hardwired to set the table to fill the available view. Most of the time the tableview is the top view itself and that works. The main function of the UITableViewController is to position the table so if you're using a non-standard layout, you don't need it. You can just use a generic view controller and let the nib set the table's frame (or do it programmatically). Like I said, its easy to think that the delegate and datasource methods have to be in the controller but they don't. You should just get rid of the tableViewController all together because it serves no purpose in your particular design.
To me, the important detail in Apple's documentation is that they advise you not to use "view controllers [i.e., instances of UIViewController or its subclasses] to manage views that fill only a part of their window". There is nothing wrong with using several (custom) controllers for non-fullscreen views, they just should not be UIViewController objects.
UIViewController expects that its view takes up the entire screen and if it doesn't, you might get strange results. The view controller resizes the view to fit the window (minus navigation bars and toolbars) when it appears, it manages device orientation (which is hard to apply correctly if its view does not take up the entire screen) etc. So given how UIViewController works, I think there is merit to Apple's advice.
However, that doesn't mean that you can't write your own controller classes to manage your subviews. Besides the things I mentioned above, interacting with tab bar and navigation controllers, and receiving memory warnings, there isn't really much that UIViewController does. You could just write your custom controller class (subclassed from NSObject), instantiate it in your "normal" fullscreen view controller and let it handle the interaction with your view.
The only problem I see is the responder chain. A view controller is part of the responder chain so that touch events that your views don't handle get forwarded to the view controller. As I see it, there is no easy way to place your custom controller in the responder chain. I don't know if this is relevant for you. If you can manage interaction with your view with the target-action mechanism, it wouldn't matter.
I have an application where I did use 2 separate UIViewController subclasses below another view controller to manage a table view and a toolbar. It 'kind of' works, but I got myself into a massive pickle as a result and now realize that I should not be using UIViewController subclasses for the sub controllers because they contain behavior that I don't need and that gets in the way.
The sort of things that went wrong, tended to be:
Strange resizing of the views when coming back from sub navigation and geometry calculations being different between viewWillLoad and viewDidLoad etc.
Difficulty in handling low memory warnings when I freed the subview controllers when I shouldn't have done.
Its the expectation that UIViewController subclasses won't be used like this, and the way they handle events, using the navigation controller etc that made trying to use more than one UIViewController subclass for the same page tricky because you end up spending more time circumventing their behaviour in this context.
In my opinion, The Apple Way is to provide you the "one" solution. This served the end-users very well. No choice, no headache.
We are programmers and we want to and need to customize. However, in some cases, Apple still doesn't want us to do too many changes. For example, the height of tab bar, tool bar and nav bar, some default sizes of the UI components(table view), some default behaviors, etc.. And when designing a framework and a suite of APIs, they need to nail down some decisions. Even if it's a very good and flexible design, there is always one programmer in the world wants to do something different and find it difficult to achieve against the design.
In short, you want a table view and a label on the same screen, but they don't think so. :)