multiple inheritance in objective-c with superclasses already made - iphone

Say I want to create my view controller class with 2 superclasses; UIViewController and UIView.
is this possible? or is there another way of getting round this?

Multiple inheritance is not supported by Objective-C (hopefully, because multiple inheritance is generally synonym of bad design and also lead to potential complex problems like the diamond problem).
Use protocols instead if you need the concept of "common programming interface" (common API for multiple classes)
Note anyway that making a ViewController inherit UIView is nonsense anyway as this is not the same objects at all and in separate parts of the MVC pattern. (UIViewController being in the "Controller" part, probably holding behavior stuff, whereas UIView is the "View" part and not the Controller part, and only have to manage the display/visible representation of your stuff).
There is obviously some misunderstanding of the MVC pattern (omnipresent in Cocoa framework) and I suggest you take some time to read more about MVC. This may not be straightforward at the beginning if you are new to OOP but this is worth understanding as it would be easier for you once you understand it fully.

No multiple inheritance in Obj C. However you can achieve your goals using Protocols, composition and message forwarding. And might I add, just searching for the above 3 keywords in Apple's dev documentation pages is an excellent way to learn and get started.

One of the tasks of a view controller is to carry enough state so that the view can be released and rebuilt to handle low memory situations. So it is a likely a bad idea.
In general, the iOS framework uses delegates as a neat way to combine the behavior of 2 superclasses: you subclass one (or both) and have an instance of the other class as member variable. Neat and simple and probably a better design anyway.

Related

Is it right having ViewControllers with a lots of code?

I'm still quite new to Cocoa and Objective-C (<1 year). My App now has some 50+ classes, but some of the ViewControllers get quite crowded with code, like 700 lines or more.
My question is: is it fine to have a "large" ViewController or are there patterns for splitting up code into fractions? A lots of the code is implementing delegate methods, thats why I don't have an idea how to move it away.
I know, I can structurize with pragma marks though.
Thanks for any input.
EDIT (Dec 2013): there is a great article from Chris Eidhof of objc.io regarding this subject. He also talked about that subject on Macoun 2013/Frankfurt. Separating out the UITableView protocols are a great pattern.
EDIT2 There are also 2 videos on NSScreencast explaining concepts of refactoring ViewController (episode #102 and #103).
One of the most common causes of large view controllers that I have seen, is lack of separation b/w Model and Controller in MVC architecture. In other words, are you handling your data in your view controllers?
If yes, rip out the model component from VC and put it into separate class. This will also force your thinking towards a better design.
For reference, In View Controller:
Handling of all changes in the UIView and the UI elements contained within.
All animation, transitions and CALayer operations.
In Model:
All processing of data, including sorting, conversion, storage, etc.
IMHO, 700 lines is not (yet) huge for iOS code, I've seen and handled much worse. Of course, if all your VCs are this big, you have a problem.
You should definitely use and abuse #pragma mark, it's very useful under Xcode at least.
Then if you find you got too much code in one file, you can extract functionality to classes or categories, as better fits.
Creating classes can be very rewarding in the long term to manage recurring tasks in projects (ie connecting to webservice, parsing XML/JSON, interacting with SQLlite, logging, etc...). If you are doing recurrent iOS programming, you can create a 'common' library of useful code that way.
Creating categories, especially on UIViewController can help reducing boilerplate code that takes a lot of place. You can (and probably should) also create a common base UIViewController for your app, that will handle stuff like rotation, maybe logging, navigation, etc... in a centralized part of the code.
You should try to identify what your ViewController is really doing.
If you can separate some concerns you can move them to classes of their own. Find out which properties and ivars are used by the viewControllers methods. If you can find a subset of functions, that use a common subset of ivars/properties, these together are very likely to become a class of their own. The controller would then own such a new class and delegate work to this.
If your ViewController is managing some sort of state, eg. you find the same switch statement or if-chain in 2 or more methods the STATE pattern could make your VC much more readable. But basically you could use any pattern that helps to reduce the VCs responsibilities.
IMHO the ViewController is the place were you would connect the model to the views. Propagating model changes into views and handling user interaction with the views are the only things, that should happen there. All other responsibilities, like calculation, network transfer, parsing, validation... should happen in different classes the VC uses.
You might like the book Clean Code by Robert C. Martin. He explores in depth how code could be structured to increase it's readability and reusability.
You can distribute the code using categories depending on the functionality. Refer http://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/Category.html
Prefer the use of NSObject class to manage part of your view controller functions. Main reasons code is more clear and easier to debug

What is your rule for splitting View Controller class into VC and custom class?

AFAIK view controller classes should be used for managing their views, IBActions, IBOutlets and other view-screen related stuff only. This means that view controller class should be as lightweight as possible, only concerning about managing its root and inner views. However, sometimes we are tempted to leave the code inside view controller class and not to move to other custom class.
Currently, I always create custom classes for models(database tables or custom objects), parser wrappers, heavy computations and for other logic that is more or less big and might be considered as a separate class. However, very frequently, I'm leaving some relative small computations, simple checking, simple download and other small code stuff inside view controller classes, because I'm lazy (and who is not?) and I'm not comfortable with having a bunch of tiny classes just because, theoretically, some several code statements does not belong to some view controller class. I understand that those tiny classes might evolve to bigger and real classes later, during other versions of an app, but however, might not.
IMHO, if you will be very concerned about the 100% pureness and cleanness you will spend more time (well, at least during initial versions of the app), but you will never know if the product will evolve or if it will be abandoned. There's always some trade-offs the developers are facing with.
It would be interesting to hear, what in-house rules do you use for designing your classes.
Two questions really that when/where you should do something which is whether you've stuck to the pattern or not.
And how
How is much less clear cut, particularly when practicality and pragmatism start getting in your face.
We tend to go for a static class for simple stuff e.g. a DateUtility class for parsing and formating dates in different formats.
And Aggregation for larger stuff, i.e. a downloader.
If you want reuse, decouple is the basic rule, so just because something was big wouldn't necessarily mean a different class.
Personally i like to have a strict class separation also if that means have a huge amount of files :(
Every object has its purpose and if i found some really generic operations i prefer create an "helper" class where encapsulate methods that cannot be specific of a context.
The really difficult step is to be strict on your decision and don't be lazy :) because by your question it's clear that you understand how it's important be rigorous on your code!

Code reuse in iOS applications

i am very new to ios development, rather i have just started work on my first app. Now my app has a home button on almost every page and behind that button the same code snippet is called to move to the home screen. This is a lot of duplicate code in every controller that has a home button. And it is just an example. There are many other scenarios like this and programmer still learning to code, i think its bad practice as any change will have to be made separately on every controller.
So my question, what are the best practices in scenarios like this when coding for ios??
One easy thing to do in this situation is to make a UIViewController subclass (MyAppMasterVC, for instance) and define your button as so:
- (IBAction)myCommonButtonAction { // code and such }
In all of your view controllers, inherit from this one instead of UIViewController (a la #interface MyNewViewController : MyAppMasterVC).
The first thing to do is to learn more about OO programming and class hierarchy, and understand how you can make a common base class for all of your similar controllers.
Software development for iOS in this sense is no different from any other software development. Simply merge your logic into some common class or function, and use that as it deems appropriate. It often turns out that you don't know what part could be common and reusable until you write multiple pieces of code, and only then you realize that it all could be one function. The process of organising existing code, cleaning it up, making it more readable and reusable is called code refactoring. There are a lot of books on refactoring that explain different design patterns, techniques and processes of making your code better. I recommend you read some of them to get a better picture.
This problem is language/platform agnostic. The term many use is 'DRY', an acronym for 'Do not Repeat Yourself'.
Here is a SO search. This should help you with the typical problems and uses, so you can better determine whether you can, when you should, and how to approach this type of problem.

model view controller question

I've been working on my iphone game recently and came across a forked road when deciding the design of my various classes. So far I've adhered to the MVC pattern but the following situation had me confused:
I have 4 buttons displayed visually. Each button though consists of a container UIView (which I've subclassed) and 2 UIButtons (also subclassed) as subviews. When you press a button, it does the flip effect plus other stuff. The user input is using target-action from my container UIView to my controller. This part is ok, the following part is the debatable part:
So I've subclassed the container view as well as the UIButtons and I need to add more data/methods (somewhere) to do more things. Putting data that needs to be serialized and non-rendering related code in the view classes seems to break the MVC design but at the moment, it makes the most sense to me to put it there. It's almost like my subclassed views are their own little MVC's and it seems neat. Separating out the data/methods from the view to my main controller in this case seems unnecessary and a more work. How should I be doing it?
Thanks heaps.
The MVC pattern is quite useful because it lets you reuse at least 2 parts of the MVC model (usually the model and the view) so usually, the best way to write clean code is avoid the use of inheritance and use instead delegation (based in protocols) and dependency injection (for the services) so you can generate unit tests for your systems and a better way to upgrade the develop of code
Here are some interesting articles:
when would I use the delegation pattern instead of inheritence to extend a class's behavior?
Inheritance is evil, and must be destroyed
Dependency Injection

Maintaining Single Responsibility Principle (SRP) with UIViewControllers

Sticking to Apple's guidelines, I create one subclass of UIViewController per screen of my iPhone application. However I consistently find that these classes become very large, both in terms of sheer lines of code and number of member variables.
By definition they end up being responsible for quite a number of different concerns (e.g. view life cycle, mediating between views and models, sometimes touch handling, control logic, managing alerts and other UI state).
Not only does this violate the Single Responsibility Principle but it also results in large swathes of code which are near impossible to unit test.
What responsibilities/concerns do you tend to divide off into new classes? What kinds of responsibilities do you think make good candidates for clean separation in the case of UIViewController subclasses?
This is an interesting question and I also struggle on how to properly separate responsibility. It all depends on the context but since testing subclasses of UIVieController can be a pain I try to move as much as I can into model classes. In the spirit of Skinny Controller, Fat Model.
When it comes to tables I have created a base model class for handling all the table view stuff, basically encapsulating what you get when you create a new Navigation Based Core Data project. The in the controller I just forwards the calls to my table model.
I'm trying to keep the methods of the controller as small as possible. Depending on the context I may have several model classes, each responsible for a specific part.
I have also looked into the possibility of using controller factories for getting detail controllers for certain data models.
UIViewController *detailController = [self.controllerFactory controllerForItem:item];
[self presentModalViewController:detailController animated:YES];
This way I can unit test that I get the proper controller for a specific data item without having to involve the parent controller.
With mine, I'm creating categories, abstract parents and using a variety of patterns I've learned in the Java world to reduce complexity and code duplication. But when it comes down to it, I still have one view controller per screen because every screen has at least one thing on it thats unique in some way. There just might not be much code left in the controllers thanks to the infrastructure I've placed around them.