Search code examples
iosobjective-csubclasscocoapodssubclassing

Customising or subclassing a CocoaPod library


The problem can be simplified like this: our library has 3 view controllers - MainController, SecondController, ThirdController. MainController is what we create an instance of in our personal project; it has a button that transitions to SecondController which has a button that transitions to ThirdController. ThirdController has a button that is hooked up to a method:

-(void)buttonPressed{
    NSLog("Button has been pressed!");
}

Let's assume that MainController imports SecondController.h, and SecondController imports ThirdController.h.

We want to keep the library unchanged except for overriding buttonPressed so that it presents a view controller from our personal project, so we subclass ThirdController as CustomThirdController and override buttonPressed to do what we want. If we now import MainController.h to our project and create an instance of MainController, it will not be using our new CustomThirdController subclass. How do we use our subclass without subclassing all 3 controllers from our library?


Solution

  • Fork it and change it, introduce delegate or add more options for customization. If you improve it you can send a pull request back to author.

    Update:

    For monkey patching, use category in case if you want to replace a single method in existing class.

    In the worst case you can resort to method swizzling.