4 ms·
I think that most "massive" view controllers come into existence because many developers don't realize that you can avoid them by combining two features of Obje
by LinaLauneBaer 13y ago
I think that most "massive" view controllers come into existence because many developers don't realize that you can avoid them by combining two features of Objective-C: Class extensions and categories.
The ability to add methods to existing classes is maybe the most misunderstood feature. People tend to see categories as "bad" (because they "pollute" the global namespace, …).
There are basically three ways to reduce view controllers. If applied correctly your view controller will be much more happy.
1. Replace "helper" methods in your view controllers with categories where it makes sense. Good candidates are methods which do not mutate the view controller. For example: Many view controllers I have seen have helper methods that create NSAttributedStrings based on a few parameters. This does not belong in your view controller. Make is a category of NSAttributedString instead and call it from your view controller. Also, every method that does not use "self" in it's implementation should be a category method on a different class.
2. You can divvy up our massive view controller in multiple "components". You should not create new classes for each component. Make a category on your own "massive controller" class for each component instead. Yes! There is no need to "externalize" something in multiple "component" classes. Just identify the different components that make up your view controller and create a category for each component. You can even split your massive view controller up and put each "component category" in it's own file.
3. Use class extensions to give each "category component" it's own state: You can have multiple class extensions per class. I usually have one class extension per category to give each it's own storage/state. If you do it this way then your massive view controller becomes modular as well…
The three steps above make your view controller more testable. Remember: approx. 25% of your view controller code actually belongs in categories on UIKit/Foundation classes. Categories on these classes can be tested extremely easy since they have no dependencies.
So before you apply MVVM try to write good view controllers in the first place.
- zxzxlch 13y agoDo you have links to source code that practices this? It'd be very helpful to learn by example. Thanks!