'logic' in view or view controller? - iphone

I aam planning to write a lcd numeric / 7 segment display for iphone.
(a display that consists of several numbers, each consisting of 7 (dash) segments.)
My question is, after mvc pattern, where does the 'number parsing' code belong? View or its controller?
So, should the controller pass the view just a number to display, letting the -drawRect method find out which segments to lighten up?
Or should the controller pass the view directly, which segments to lighten up, after finding that out in a method within the controller class?
As i learned so far, the controller is responsible for all logic things. But i'm not sure if that kind of logic is also meant by that.
Oh and by the way, should the controller just set properties on the view, or would it be better to call the controller as a delegate from within the view class to fetch the data?

I would say that the view should be figuring out which segments to draw. Ideally, you would be able to turn your app into an analog clock by just swapping out the view (since the numbers delivered from the controller wouldn't change.) While you don't want your view performing business logic, "visual" logic (how data should be drawn) is definitely within the purview of the view.

Related

1 ViewController per view?

I wanted to know if I have to create a new ViewController for each view I have. Let's say I have 3 views do I need 3 viewControllers or does 1 ViewController can manage all 3 views?
Edit: Views are Objects that I create with .xib file so following the description given me by Xcode 4.3.3: represents a rectangular region in which it draws and receive events.
My situation : What I want is the main View showing 3 buttons, each button leads to a new View. That's about it each of the 3 views will have about the same thing, a tableView to display data parsed from an XML.
Thanks again!
EndEdit
Thanks
Both are possible, depends on your needs. View controllers can easily manage more than one (sub)view (e.g. every UI control subclasses UIView and you can have many in a single view controller). Sometimes it's more convenient to put views in different view controllers, sometimes it's not.
Depends on your situation and what you want to present to the user. If those 3 view controllers have very similar functions and only minor differences, then you could use the same class and have an instance variable to indicate which mode you're in. For instance if you have a list of Songs, Playlists or Videos, those could be the same class, with an enum variable to differentiate between the 3 modes. If your views are significantly different however (like a Song list and a Video player) then you should usually have separate classes for them.
For iOS, general best practice has been for a single view controller to manage a single "screen (or "window", but of course there is only one of these on an iOS device). This view controller may support a variable number of view objects (certainly not a ratio of 1:1 views/view controller).
As of iOS 5, nesting multiple view controllers managing multiple views in single window is now technically supported, but I still consider it a practice best avoided.
One window = one view controller = multiple views.
In one view controller you can manage any number of views.
It is preferable to use a viewcontroller per view. the advantages of the approch is as follows:
Any time you can convert the Template of the application. (eg. from table view to tabview or split view can make quick change)
with each view controller you follow the MVC architecture.
if you have n controller than try to manage n MVC model so that you can shift any model any where easily.
Memory management will be easy (Push and Pop manage memory automatically.)
if we have sigle view controller and n number of view than it will be quite difficult to manage memory.
Also we need to keep the screen ID for each view and need to mantain also their switching.
there are N number of advantages if you use N numbers of viewcontroller over N number of views.

XCODE : Using TabBar to view two same ViewControllers that show different filters on the datasource

I have a problem with my App for iPhone.
Enviroment: I have a TableView, that operates above an MutableArray datasource. An example would be Lap Times for Go cart pilots.
Datasource: I record lap times from both training sessions and from race and qualifying. I consider race + qualifying as one subset of data and training sessions as another subset of data because I think there is big psychological effect and my drivers have slower laps when racing because of fear of crashing into others. At this time I record both data in one array with a variable of Bool "fromRace". So I can filter racing and out of race times.
Human Interface: I created a TabBar that shows racing times in first Tab and training times in second Tab. It feels, like those Tabs contain basically the same view and operate on same data which I just filter using the same view controller since all the methods are the same.
Is it programatically correct to create two separate view controllers and two separate arrays for the datasource basically duplicating the code? Or try somehow to try to discover from which tab I came and alter the data presentation accordingly using just one view controller?
I hope I am clear on what I ask for.
Yes - broadly speaking, a UITabBar is used exclusively to switch between view controllers. That's how it's designed to operate - you load each 'slot' in the tab-bar up with a view controller.
That doesn't mean you have to create two separate view controllers - you could create two instances of the same view controller, and have some flag passed in upon initialisation that would display the data in a different way.
If you just wanted to have a single view controller adapt to display the data in different ways a UIToolBar would be a more appropriate UI element (perhaps with a segmented controller at the bottom).

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.

iPhone One controller, multiple views

I'm rather new to iPhone development, and am wondering how to load multiple views from a single controller.
I come from a c# background and still trying to get my head around how things work in ObjC and the iPhone worlds.
As a basic example of what I am trying to achieve, lets say I have a ClockController, the clock controller has the base methods for calculating the time.
Now what I want to do is have this controller capable of rendering any number of views which support the ClockContollers underlying interface.
Lets say I have one view that renders the clock as a digital output and another that renders it as an analog display (basic example I know).
How would one achieve this?
Sorry if this is a very basic question, but I am quite new at this.
Thanks in advance
Here is my understanding of how to apply MVC to your example:
The clocks that you draw on the screen are inside views which are each backed by an instance of your clock view controller class. These controllers each interact with a clock model and update their views as appropriate. It is in this class that a property would be set that determines if the clock is digital or analog.
It sounds like your "ClockController" is really a model/data class. You can have just one instance of this model class or one for each of your clock view controllers (if they have different times).
In my apps I have many instances of a single view controller which then utilizes different or multiple views to display the UI. You can take a view and all its subviews and add it to the view controller using addSubView, and remove that view and all its subviews using removeFromSuperview. This works well if the view is only displaying info and is subclassed to handle its own differences from the other views that the view controller has to handle. In you case, an analog clock view has to draw itself one way and the digital clock view draws itself in another. The controller merely has to tell each view what the time is, and the view handles the translation to visual data. If your view accepts input in the form of a user dragging the analog hands to set the alarm, then the view subclass needs to read that input and then translate to an alarm time and pass it back to the view controller. The controller doesn't need to know which type of clock the user is interacting with, but only sees an alarm time it needs to add to its alarm queue.
However, when I have views that utilize very different UIs or for different purposes, I generally prefer having one view controller per set of views. Basically, I try to use my views as a display and my viewControllers as the manager of data related to that view (and any other views that can be backed by that same data).
For example, my game has one view controller for playing, another for the high score table, and yet another for the settings.

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