What's the best practice to make it easy to reuse a bunch of code across multiple controllers?

I'm new to programming and wondering about some (best) practice:

Let's say we have an application with multiple view controllers. In our case, most of them need functionality to alert the user about certain circumstances, use an activity indicator, or depend on other similar general functions. So far, I've learned how to implement such methods, but then I just copied the whole bunch of code into each view controller when needed. This fills each view controller with a lot of extra code. I know it is possible to make the code "global" by moving it to the top of the view controller, outside of the class clusters. But since we need to ensure that certain subspecies are added to the correct view controllers when these methods are called, I'm not sure yetthat the best way to go - in general - would be.

Is there a common practice that differs from my approach in defining such - let's say - alert behaviors (defining a variable / constant and its required methods) that are used across multiple view controllers?

+3


source to share


2 answers


Objective-C provides two general ways to reuse code:

  • Base class inheritance and
  • Using a common function.

The first case is simple: if you need specific functionality across multiple view controllers, create a base view controller with shared methods, and then retrieve the other view controllers from it:



@interface BaseViewController : UIViewController
-(void)sharedMethodOne;
-(void)sharedMethodTwo;
@end
@interface FirstViewController : BaseViewController
...
@end
@interface SecondViewController : BaseViewController
...
@end
@interface ThirdViewController : BaseViewController
...
@end

      

The second case can be implemented either as a helper class using class methods (i.e. with +

instead of -

), or with free-standing C functions.

+3


source


You should look at what can be moved from the controller layer to the presentation layer. It looks like you are reusing a bunch of views, so I would create subclasses UIView

that I can implement myself . Then in the view controller you can handle when the views and the data associated with them should appear, but you don't need to rewrite how to implement the views.



0


source







All Articles