iPhone GLPaint sample has architecture design flaw? - iphone

I'm brand new to iphone dev, but am familiar with the MVC pattern. Can anyone please explain why the GLPaint sample class PaintingView.m (the View) actually gets the data required from disk to write the "Shake Me!" text? The Data is the Model and should be read from the disk by the controller and passed to the View to render IMO. Correct?
Also, the Controller is adding UI controls to the view (color palette segmented control) - shouldn't the view be drawing this stuff?
Is this a bad example Apple have provided?
Thanks.

It's a good example of how to use OpenGL, but it's a poor example of MVC. I imagine that since MVC wasn't the focus of this example, it wasn't really written with it in mind.
At the end of the day, if the example works and shows you how to use the thing it's being an example of, then it's done its job.
I'm sure there are other examples of MVC out there from Apple that are done properly.

Thanks, I think it's a bit of a hack, but:
http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaDesignPatterns/CocoaDesignPatterns.html#//apple_ref/doc/uid/TP40002974-CH6-SW8
Combining Roles
One can merge the MVC roles played by an object, making an object, for example, fulfill both the controller and view roles—in which case, it would be called a view-controller. In the same way, you can also have model-controller objects. For some applications, combining roles like this is an acceptable design.

Related

How to avoid bloated ViewController in MVC with Swift?

I am trying to keep to the Apple MVC design pattern where the view receives input and passes it on to the controller. To keep the controller thin and to avoid it turning into a bloated GodClass doing all the work, I am attempting to create a subclass of UIView and to receive user input there to be passed to the controller for processing. But I am running into problems with how to best do this in Swift.
In order to pass the user input from the view to the controller my UIView subclass will need to communicate with the associated ViewController, but I've seen posts on SO about how that is not recommended. This Q&A, for example, advises that this is bad but suggests a delegate approach. A comment from the same Q&A also notes that this is bad.
Apple's own MVC example doesn't demonstrate a separate UIView subclass, but uses the existing UITableView, which is all coded within the parent UIViewController, making it a bloated, rather than a thin controller.
How to best approach this?
I recommend you read the apple's doc on MVC pattern since I noticed you do not really understand the principle of the pattern: Model-View-Controller
In order to build lighter ViewController, look at this issue: Lighter View Controllers
You may also interested in MVVM (which used in Cocoa&CocoaTouch for VC thinning)
have a look at this article: Introduction to MVVM
Your experience with bloated View Controllers is not necessarily the fault of your misunderstanding the MVC pattern. The iOS developer Ilya Punchka writes about this in his tutorial post about View Controller Thinning and writes:
A lot have been said on this topic already, even more will be said in future cause unfortunately there is no silver bullet and view controller still stay massive in many projects. Recently Andy Matuschak presented Let's Play: Refactor the Mega Controller! a live coding session on this topic. So you can see it's a well know and still actual problem.
The situation isn't helped by Apple's sample code which also demonstrates massive view controller syndrome! Check out the above links (although the first is in Swift 2.0 and I've had troubles updating his dependancies to Swift 3.0), they both give useful oversight on some ideas around this subject.
I'd recommend taking a look at LetsBuildThatApp episode "Swift: Firebase 3 - How to Refactor View code out of Controller (Ep 23)" here:
https://youtu.be/F3snOdQ5Qyo
Shows a pretty good way to refactor the View code out of the Controller.

Xcode 4 organization, Views and Controllers

Thank you for reading this.
These are my first steps in the iPhone Ipad app programming.
In order to learn from scratch (and because I know my app would need dynamic views), I decided not to use Interface Builder.
My question is(regarding the fact that I don't use IB): how would one use Views and Controllers?
I think I understand the MVC concept as it is repeated over and over again in the tutorials I follow, but after the "MVC explanation" part, nothing is made to make it clear "on the field" and closer to the real world (Earth being Xcode here).
Worse, sometimes it seems that some tutorials mix these two concepts up and use one word to say the other.
I read around here a lot of questions (and answers of course) based on the matter but I still don't get it. Sometimes it's too generic, sometimes it's too specific (for me at least).
For what I think I understood, the UIView is the static View when the View Controller is the logic which links the View to the data and those 3 concepts must be separated.
This separation, while a bit clearer with the use of Interface Builder seems to get quite blurry when you code everything as it becomes a virtual soup.
Technically, should I create a specific ".h" and ".m" file for each View AND ALSO for each associated Controller?
If I understand the MVC pattern, it's seems that I should but when I follow tutorials (without IB) it is never the case, view and controllers are created and manipulated within the same implementation files.
Any high level (I'm a noob, don't forget) but still applicable explanation of the use and best practices?
Let's say I want to create a simple app with a green view I can swipe to get to a red view.
I know for sure that I would need at least an:
xxxappDelegate.h
xxxappDelegate.m
xxxView.h
xxxView.m
What else?
1)Where should I put the the second view (along with the first one in "xxxView" or should I create another class h and m file?)?
2) What would the controller(s) do, for that kind of application? In which files would they be created and in which files would they be invoked and how would they "control" the related view?
3) Mainly, regarding to MVC pattern and the fact that there would be no IB, how would you organize that app?
I know it's a lot if you go into the details and code but that's not the point here.
Thank you. This - as simple as it seems - would be of a great help and is not as easily found in tutorials as you might think.
I understand the tutorials I read but they are so particular. As soon as I try to create something on my own which is not a "Hello World" screen, I realize that something is missing, logic wise.
Thank you very much for your help.
Sorry, but I can't get past your first paragraph. If you don't use Interface Builder, you are not going to be a successful iOS programmer. It's that simple. The best advice I've ever read about this is in this Aaron Hillegass interview:
Experienced Cocoa programmers put a lot of the smarts of their application in the NIB file. As a result, their project has a lot less code. Programmers who have spent a few years working in Visual Studio get freaked out. They ask me stuff like, "Can I write Cocoa apps without using Interface Builder? I like to see the code. Maybe I can just explicitly create my windows and the views that go on it?"
It is difficult to explain how the NIB file (and a few other scary ideas) create leverage. It is that leverage that enables one guy in his basement to compete with a team of engineers at Microsoft or Adobe. It is like I showed a chain saw to a early American colonist, and he said, "Can I cut down the tree without starting the engine? I don't like the noise. Maybe I can just bang it against the tree?"
Yes, it's hard to generalize after reading specific tutorials, but you will learn. I thought the learning curve was insurmountable when I first started, but if I can become a programmer that gets paid to write Cocoa software, you can too. Just keep reading and practicing. Don't fight the tools--use them.
Early:
In order to learn from scratch (and because I know my app would need
dynamic views), I decided not to use Interface Builder.
Later:
As soon as I try to create something on my own which is not a "Hello
World" screen, I realize that something is missing, logic wise.
I think what is missing logic wise is that you have accepted your assumption that Interface Builder was a crutch and that to learn "from scratch" you had to avoid using it. You are trying to learn the MVC design pattern but you are not willing to use the tools that have been designed to support it.
In Apple's own documentation they discuss the fact that sometimes there is value in having combined roles—Model Controllers and View Controllers—and that is worth reading, as it may explain some of the code examples you're reviewing. But my primary advice would be: before assuming you know better than the people who built the tools, trying using them the way they recommend. It might be an eye-opener.
Additions later:
OK, so to try and actually answer your questions...
1)Where should I put the the second view (along with the first one in
"xxxView" or should I create another class h and m file?)?
If I am understanding correctly and the two views you are thinking of here are the red and the blue displays to the user, you wouldn't have a second view—what you would do, whether in IB or in code—is to have an element in your view on which you changed a colour property... This would be done programmatically whether you were setting up the parent view in IB or in code.
2) What would the controller(s) do, for that kind of application? In
which files would they be created and in which files would they be
invoked and how would they "control" the related view?
There would be a view controller that would implement the gesture support, and would provide a method for changing the colour of the item in the view between blue and red when that swipe gesture was successfully received. I would have a ViewController.h and and ViewController.m. I think if you were implementing the View entirely in code, it would be implemented in the ViewController.m rather than having a separate View.m. (If you were using IB, you would have a ViewController.h, ViewController.m and ViewController.xib, with the latter providing the basic setup of the view elements and layers.)
You would create a ViewController instance in your AppDelegate.
3) Mainly, regarding to MVC pattern and the fact that there would be
no IB, how would you organize that app?
As above.
If you really insist on going without IB (and I agree 100% with SSteve) then in addition to the files you list you will also want to use a UIViewController. Now, it is important to know that you only need to create header and implementation files when you are adding or changing default behavior.
In you case, the view can probably just be a generic UIView, so you wouldn't need the files. What you would do is subclass UIViewController, and put the swipe logic there. In the swipe logic code you would probably just change the background color of the view.
You would instantiate the view controller in the delegate (in this case anyway) and create the view in the view controller's loadView method. That is required since you won't be using IB.
Personally though, I think that IB does a great job of encouraging proper MVC patterns, and if you are just starting then you should go with IB.
In practice you mostly do not make classes for views, unless they need to do custom drawing or display.
For lightweight configuration of views, that is often done in the viewController's viewDidLoad (or I guess in your case loadView) method.
Yes it's a good idea to keep model and view separated, but that's also balanced with the equally good idea to reduce the amount of code that exists. The less code that is written, the fewer bugs you will have.
Since you are just starting out at this point I would absolutely start by using ARC, and using IB - even though I'm sure you're tired of hearing that from everyone, I'll give you an alternate take. Less code means fewer bugs. And the fact that so many experienced developers are telling you to use it should be a giant clue about what a productive path forward is. I mean, are you doing this to build applications or learn every corner of the UIView class?
To speak to your code example, you do not need the UIView custom class. Just create use a UIViewController's main view as a container view, place a UIView inside with the background set to red. On swipe (using a gesture recognizer attached to the container view) call the UIVew method to swap in a new green-background UIView for the existing red view, you can even define the transition style.
Or create a scroll view in the container view, set up the red and green view inside the scroll view, set the content size and enable paging on the scrollview.
Or create a custom UIView class as you had, listen for touch events and slowly adjust two subview positions to follow the drag action.
Or use an OpenGL backed view, and based on the gesture recognizer pan the scene you are observing with two triangles for a green rectangle and two triangles for a red rectangle.

How mvc pattern is implemented in iOS user interface? (view-based XCode temlpate)

I'm new to iphone development. There's a lot of books on this topic available. But most of the beginner's guides are mostly concerned with Interface Builder usage and lack the information about existing built in XCode code templates or something that could help me in understanding MVC implementation in code. I found that it is possible to write working iOS program without ViewController at all. Well, it seems to me like that after working with the sample code called ViewTransitions.
So, the question is - why is that possible to avoid ViewController implementation in a program that has an interface with a button? If the answer is going to be too long, could you please recommend kind of tutorial or manual covering this topic.
Thanks in advance.
#user697562's answer is essentially correct: in the case of ViewTransitions, the role of the controller is played by the app delegate. The app does next to nothing -- it just switches betweeen two views to demonstrate several possible transition effects -- so a UIViewController isn't really needed there.
Notice that there's also nothing in ViewTransitions that you could really call a model object. If you're looking for a strong example of MVC, ViewTransitions isn't the best project to look at. Other sample projects, such as TheElements, give a better demonstration of MVC in action.
There is a concept called delegation. A concept which helps maintain MVC. It helps to keep the model separate from controllers. For eg: - UITableView/UICollectionView , which knows how to display the data and other ui stuff.
But it does not know which cell to display or what data to display at a particular index. And this is where delegation and the delegate object comes into place. UICollectionView handles all the view part whereas all the non view part is handled by the delgate object, which gives the required data for the view. This way a delegate(usually a separate view controller) acts as a data source and UICollectionView as a ui renderer.
in ViewTransitions, there IS an App Delegate, which is kind of your sole "controller". Even ViewTransitions has:
transition.delegate = self;
IOS is a bit different from some frameworks in that you aren't as "in control" of what is going on. It often uses a delegation model where you set your code as the delegate, but it (IOS) is in control. Still, you can write in MVC style, it's just your "C" isn't fully in charge.

How does the Model-View-Controller pattern apply to iPhone development?

Recently I've been reading up on the MVC pattern and wish to apply it to my iPhone development. However, there seem to be so many variations of the pattern that I'm not sure exactly how it should be applied.
As far as I gather, the view will notify the controller of any actions which have been performed and the controller will in turn update the data model (if required). The data model will notify the view whenever a change to the data occurs and the view then updates it's display of the data appropriately.
In this basic model, the controller only has knowledge of the data model. However, I can't seem to figure out how to employ this design within my iPhone app.
The following page suggests an alternative version of the pattern where the controller has an awareness of both the data model and the view and all communication between the model and view is performed via the controller. It also seems to suggest that the model and view have access to the controller. Would I be right in suggesting that the data model interacts with the controller via some form of notification (notifications or KVO) and that the view interacts with the controller via actions?
Is this second model correct?
http://www.bogotobogo.com/DesignPatterns/mvc_model_view_controller_pattern.html
Many thanks,
Danny
I found Paul Hegartys explanation on MVC in iOS very helpful. see his Stanford iTunes U video. MVC starts at minute 22.
edit
The link of the video doesn't bring you there as expected. it is 1. Introduction to Cocoa Touch, Objective-C, Tools, and MVC (September 21, 2010)
MVC has been around for a long time so there are many variations (or misquotes) to the pattern. Although, the concepts are much the same for most MVC implementations I have seen.
I would focus on how Apple defines MVC. Which can be found in the Cocoa Design Patterns guide and from sample code downloaded from the SDK site (MVCNetworking example).
With iOS you will often will have Models and ViewControllers(which are a merged role of both the controller and the view).
Also, Martin Fowler has some great MVC stuff in his GUI Architectures.
iOS development is very much orientated towards the MVC pattern.
It is usually done with viewControllers and a model. The view is build in Interface Builder, assigned to the controller and the model part is retrieved from elsewhere.
I would say that for Cocoa-Touch the second "version" of the pattern is the one that best describes what usually goes on.
The idea behind MVC is that the model and the view is reusable, but the controller is often fitted to the problem at hand.
This is also true for iOS development, especially if you use interface builder.
The view is hooked up to the viewController via actions/delegates and the model either broadcast its changes through KVO notification or by the controller pulling new data.
There is tons of code available from Apples developer portal and you should start out by looking at some of that code. Having your eyes and mind tuned to looking for the MVC pattern you will see they use it constantly, with the delegate pattern on top to provide event better abstraction
In my opinion, second one is better. Model and view should be separated completely. If view receives notification from model, the view will depends on design of model. By placing controller here, tightly coupled circular-dependency created.
Finally, each part cannot be developed independently, divide-and-conquer strategy is just impossible to use.
My advise for general cases:
Make view and model passive and independent as much as possible. Major mutation must be done with only external manipulation. It should not be changed actively.
Make controller actively controls both of them and other controllers.
In iOS, a UIView is a view which is fully passive. In most cases, all major mutation always done externally by UViewController. And model part should be implemented yourself completely as you want. (Or you can integrate models into controller if it's small enough, however, I don't recommend it)
In some big featured UIView, a sub-scale MVC patterns are used. Fractal!

How to achieve reusable code when doing everything programmatically, without using Interface Builder?

I'm the programmatic guy, and I simply don't want to use Interface Builder. I feel out of control, and besides that my GUI is about 90% custom all the time.
Literally every book does everything in Interface Builder and claims that this is the one and only great way to have real MVC going on.
Example: One of those books mentions that programmatically creating an UINavigationController with an Root View Controller and everything else that belongs in there is a big mess and won't be reusable when porting to the iPad, while doing this in XIB is a clever decision. Then the port to iPad using UISplitViewController will be a simple task.
So when I make iPhone apps and want to port those to the iPad too, what strategies work to reuse as much code as possible? I'd like to learn more about how to separate my code and achieve a better overall architectural design without using Interface Builder.
For those who want to tell me I must go with IB: Again, I do a lot of custom UI where IB is often just in the way. And not to mention all the animations. I really have my reasons. For people who make default UI IB is really fine - but please, I don't want to start a fight for IB vs programmatical UI or default UI vs custom UI! It's all about how to achieve great reusable code when doing everything programmatically, and both have their pros and cons.
Although you did not ask for it, I feel compelled to make the case for why people in general (perhaps not you) should consider IB, and then address the issue of custom components.
I use a lot of animations and custom components. And I love to use IB...
The key is to use IB for its strengths, and then decide what to do with the rest from there. What then are the strongest points of IB? Connections, placement, auto-resizing and customizations.
Connections are linking aspects of views and controllers together. It's faster in IB to drag out a few connections to delegates or references, than it is to write the code that forms the connections. And, it's a quick place to review all links to the UI you are building.
Placement IB also does well at. There's a fair amount of code involved in setting up any GGRect correctly. Not only is it easier to enter and review coordinate and size details in IB, but the tool automatically sizes a lot of elements properly for the container and the control, and offers many guides to help things line up properly - that kind of thing can take a lot of repeated testing to get right.
Related is auto-resizing. Although I don't feel that many screens can actually have auto-reiszing rules that rotate the screen and come out the other side looking just right (I almost always do rotated views as a separate XIB file), there still are a lot of shifts that can occur in the course of running your application that make it really useful to have these defined just right. The best example of this is the enlarged status bar while you are on a call.
Lastly comes customization. This again can be a lot of tedious code to write; try setting up all of the properties on a UILabel manually and it'll have you yearning for quick changes in IB.
With all that said, what is a good approach to custom components? I like to use UIViews in IB screens, with the class type set to a custom UIView that then fills out the display at runtime. But at least IB helps me get composition, placement and auto-resizing just right with minimum fuss, and also wire aspects of that custom view into a controller.
The one thing that would really lend IB to use with custom components is if it would simply let me set values for any simple properties the custom view had - then I could adjust parameters like a corner radius or whatever else I had going on.
I urge you to think on IB a little more, as it's a huge productivity boost when used correctly. There should be nothing about IB that gets in the way, it's there to boost your output.
One book I really liked was Erica Sadun's iPhone Cookbook 1st edition. It did everything programmatically.
Unfortunately the second edition is bloated.
If you reuse lots of your custom UI objects, it would make sense to write a code which
reads a plist (or a more general XML file) specifying how the custom UI objects should be placed / animated
and then creates your custom UI objects accordingly.
It's like writing a mini-xib file format tailored to your UI objects; you can also feel that you're in control of everything, as an added bonus.