Search code examples
iosobjective-cuiviewcontrollerobjective-c-category

Objective-C category calling method of a custom class


I have some classes, lets call them A, B and C, being inherited from UIViewController and some category of UIViewController that has some methods in it that have to be common for all the classes.
Category's methods have to call another methods on ViewControllers, but. Not all methods will be implemented in VCs (because they never be called in that context).
If I write method definition in category, I get an error, that method is not declared, but it is declared in VC or not declared and will never be used in that context.
Is there any ideas how to override this and share huge part of code (Navigation code) between multiple ViewControllers?

- (void)homeButtonPressed {
    NSLog(@"Home button pressed, ViewController");
}

- (void)changeFloorButtonPressed {
    [self changeFloor];
    NSLog(@"Change Floor button pressed, ViewController");
}
- (void)QRButtonPressed {
    NSLog(@"QR button pressed, ViewController");
}  

Here [self changeFloor]; is method, which is specific only to one ViewController.


Solution

  • Why note create your base class of type UIViewController, then create classes that inherit from your new base class. Each child can then implement the methods they need.

    MyBaseViewController: UIViewController

    ViewAViewController: MyBaseViewController

    ViewBViewController: MyBaseViewController

    etc

    I use this type of approach for universal apps, my child class can override the implementation from the parent or add to it.

    // common elements HomeViewController: UIViewController

    // iPhone specific implementation HomeViewController_iPhone : HomeViewController

    // iPhone specific implementation HomeViewController_iPad: HomeViewController