2

I have a group of controllers, most of whom share similar functionality.

For example:

  • Controller A has method 1 and method 2.
  • Controller B has method 2 and method 3.
  • Controller C has method 1 and method 3.

Subclassing is not really an option here as I specifically don't want Controller B to have method 1.

Protocols are not really ideal either; They still require me to define duplicates of my methods in each controller.

Is there no way to define a method in one place and mix this functionality into classes as and when required in Objective C?

bodacious
  • 6,608
  • 9
  • 45
  • 74
  • I'm curious. Can you explain how it would be a problem if controller B had a method with the same signature as method 1? – Jim Mar 06 '12 at 17:44

2 Answers2

1

Use blocks! https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html#//apple_ref/doc/uid/TP40007502

QED
  • 9,803
  • 7
  • 50
  • 87
  • 1
    Thanks for the tip... where is the best place to define a block that can be accessed from multiple files? Just in a `blocks.m` file and import `blocks.h` to the classes that require it? – bodacious Mar 07 '12 at 07:37
0

A possibility is not to use a class at all. Since I guess those methods require to access some of your controllers' fields, you can use a function that receive as a parameter a pointer to a UIViewController and access its fields from inside the function.
If each method should behave in a slightly different way depending if you are working with a ControllerA,ControllerB or ControllerC, then you can use isKindOfClass method. For example:

    void method1(UIViewController* controller) {
        if( [(id) controller isKindOfClass:[ControllerA class]] ) {
             //do something
        }
    }
Manlio
  • 10,768
  • 9
  • 50
  • 79
  • How do you have ControllerA subclass M1 and M2? Objective C does not support multiple inheritance. Did you have something in mind to work in that context? – Jim Mar 06 '12 at 17:21
  • 1
    @Jim actually I made a very big mistake. You're completely right, Objective-C does not support multiple inheritance. I edited my answer. Guess I'm really tired today. – Manlio Mar 06 '12 at 17:32
  • 3
    It's okay. I do that often, and fear some troll will immediately downvote. I've got your back :) – Jim Mar 06 '12 at 17:41