How to access other view controllers data member variables? - iphone

I want to access the value of a view controller data member variables in another view controller object.
Or is it possible to access its controls like UILabel text property?

A lot of times when I find I have to do things like that I find I can redesign the solution and the need for it goes away. Jay's law: "If it's too hard you're probably doing it wrong."

It is possible to access a UILabel of another view controller, but don't. It will lead you to very hard-to-understand bugs. Any IBOutlet can become nil at surprising times when memory is low. You shouldn't mess with another object's UI elements directly.
Your initial idea of accessing the data (model) objects, is the right one, though generally you will be better off to just initialize both view controllers with the same model object. For instance, say you have a status message that you want to show up in two different UILabels in two different view controllers. Rather than have one view controller ask the other view controller for the data, it's better to have a model class like "Status" that both views have a pointer to. Whenever it changes, they change their UILabel.
Even better is to post a notification (StatusDidChangeNotification) and just let everyone who cares observe it and update their UI appropriately.
You want to keep UI elements very loosely coupled in Cocoa. Otherwise you wind up with hard-to-fix bugs when you make what seems like a minor UI change.

You are going to have to define the property in the view controllers interface, then as long as you have a reference to the view controller in the second view controller you should be able to access it like the text of a UILabel..

viewWillAppear: is only called by the framework when you use the built-in view controller transitions like presentModalViewController:animated: or pushViewController:animated:. In other cases, you have to call viewWill/Did(Dis)Appear: yourself.

Related

iOS Development: How can I return data from a modal view?

If I have a parent view controller that displays a modal view with a textfield to collect data from the user, what's the best way to return that data to the parent view controller? Currently, I assign the parent view controller as a delegate that's called from the modal view when the user enters the data. Is there a simpler/better way to return data from a modal view?
Thanks so much for your help!
Personally, I would have the modal view dispatch an NSNotification that passes the data. A delegate works too, of course. I think that both a singleton and a delegate mean tighter coupling, but I understand that some might disagree.
But I do use singletons, too, if I need access to data stored centrally from many different places in an app. I just wouldn't use it simply to pass data from a view to another.
When needing to store and pass data around I usually have a singleton class that I use throughout my app. This keeps things a little cleaner in separating my views from each other. Here's a simple implementation:
http://www.galloway.me.uk/tutorials/singleton-classes/

How do I set up several custom UIViewControllers under one central view controller programmatically?

Being new to Xcode and Objective-C I find it hard to get my head around the Interface builder and Objective-C when doing things that are following the basic pattern. I have created a subclass of UIViewController that I want to instantiate several times to make a grid with each row being controlled by an instance of this class. So there will be one root view controller (with navigation etc) that should include/genereate all the instances of the custom sub-viewcontroller.
Now what would be the best way to do this? All examples I can find are about navigation, where one view should replace another, but I want to have all the viewcontrollers visible on the same "page". Do I need to create a nib file for the custom controller at all? I have also been thinking about using the UITableView somehow but inserting my custom viewcontroller in every row.
Any help greatly appreciated!
Apple's documentation recommends using one view controller per screen. It is possible to decompose your interface and use multiple view controllers on one screen if you have a good reason to do it, but Apple hasn't really designed their frameworks to support this, so you'll run into pitfalls if you don't know what you're doing.
In this case, I question whether each row of your grid really needs its own view controller. I find it hard to imagine a case where this would be the best choice, although it's hard to say for sure without knowing more about your app. Some things to consider:
What is your custom controller doing? Is it mostly changing the visual appearance of its corresponding grid row? If so, perhaps it would be more appropriate to subclass the UIView itself.
If this object is really behaving as a controller and not a view, consider implementing it as a subclass of NSObject rather than subclassing UIViewController. The UIViewController for your screen can capture events and delegate them to the appropriate custom controller object, or your custom views can capture their own events and notify their associated controllers of those events directly using a delegate pattern.
If you're sure you have a valid reason to implement these objects as UIViewController subclasses, check out my answer to this question.

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.

Multiple view controllers on screen at once?

I am trying to wrap my head around controllers in Cocoa Touch. The main problem is that I would like to have more than one controller “on screen” at once – I want to have a large view (with controller A) composed of smaller views controlled by their own controllers (say B). I’d like to have it this way because the division makes the code much cleaner. What’s bad is that the additional controllers (of type B) are not “first-class citizens” on the screen, for example they do not receive the autorotation queries and notifications. (And cannot easily display modal controllers, they have to send the presentModal… message to their parent controller.)
What is the difference between the A and B controllers from Cocoa viewpoint? Does the system keep some kind of pointer to the “frontmost controller”, a privileged one to which it sends notifications and such stuff? Why don’t the other controllers receive them, even though their views are on the screen? Is having multiple controllers “on screen” considered a hack? Or is it supported and I am just missing some point? Thank you.
More about the problem I am trying to solve: I am writing a simple photo browser. Photos are displayed in full screen, user can swipe left or right to change photos. The A controller takes care of the scrolling part and the B controllers take care of each photo itself.
Isolating B seemed like a good idea, since the photos are loaded from network and there is a lot that can happen, like the network might be down et cetera. In the B controller the code is fairly simple, since B only works with one particular photo. If I moved the code to the A controller, things would get messy.
The only thing I don’t like about the current solution is that I have to manually work around B not being a “first-class” controller. I have to pass some calls manually through A to B and when B wants to display a modal dialog, it has to send the presentModal… to A. Which is ugly.
There is now a first-class support for this scenario since iOS 5, it’s called controller containment.
swift controller containment
objc controller containment.
It's not closely related to the original question but important. Apple clearly states in View Controller Programming Guide that a view controller is responsible for controlling exactly one screen's content:
"Each custom view controller object you create is responsible for managing exactly one screen’s worth of content. The one-to-one correspondence between a view controller and a screen is a very important consideration in the design of your application. You should not use multiple custom view controllers to manage different portions of the same screen. Similarly, you should not use a single custom view controller object to manage multiple screens worth of content.
Note: If you want to divide a single screen into multiple areas and manage each one separately, use generic controller objects (custom objects descending from NSObject) instead of view controller objects to manage each subsection of the screen. Then use a single view controller object to manage the generic controller objects. The view controller coordinates the overall screen interactions but forwards messages as needed to the generic controller objects it manages."
However in iPad Programming Guide they also say that there may be container view controllers:
"A view controller is responsible for a single view. Most of the time, a view controller’s view is expected to fill the entire span of the application window. In some cases, though, a view controller may be embedded inside another view controller (known as a container view controller) and presented along with other content. Navigation and tab bar controllers are examples of container view controllers."
Up to my current knowledge I would not use sub-view controllers in a view controller but try to subclass NSObject and send messages to them from my main view controller.
Also check this thread:
MGSplitViewController discussion
First, and this is important, view controllers don't get "on screen" -- views do. Your "top level" controller can certainly pass along the kinds of messages you're describing to its "sub-view-controllers". In fact, this is how most apps work. Consider an app that has a tab bar, and where the views use navigation controllers. You actually have several view controllers "running" at the same time, each with its own view on screen at once -- your "root" view controller will be an instance (or subclass) of UITabBarController, which then has several nested UINavigationControllers, each which will display nested view controllers (like an instance or a subclass of UITableViewController).
You might want to read up a bit on how responder chains work. Consider a touch event. It will be generated for the view closest to the top of the stack, that can receive events, which is also underneath the tap. If that view can't handle it, it gets passed up the view hierarchy food chain until something deals with it (and then eats it).
As to the specifics of your question, on the whole, I'm not sure exactly what the strategy you describe is really doing to benefit you in terms of complexity. It depends on how exactly you're implementing things, but having separate view controllers for each little subview may require more bookkeeping code than just having one view controller that knows about all its sub-view components.
This is a pretty old question, but since I guess there are people who might face the same problem today I'd like to share my solution.
I was writing this application that had this one screen with a lot of information, pagination, controls etc. Since according to Apple's MVC documentation on the role of ViewControllers, you should not implement the logic in view itself, or access the data model directly from it, I had to choose between having a Massive ViewController with a few thousand lines of code which was both hard to maintain and debug(even with unit tests) or find a new way.
My solution was to use UIContainerView like below:
this way, you can implement each part's logic in it's own ViewController, and the parent view controller takes care of constraints and sizing of the views.
Note: This answer is just a guide to show the way, you can find a good and detailed explanation on how it works and how to implement it HERE
Actually you can make it work earlier than iOS 5, since most of us are targeting 4.x and 5.x at the same time. I've created a solution that works in both, and it works great, few apps in appstore use it :) Read my article about this or just download and use a simple class that I've created for this purpose.

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. :)