1

I have a protocol P

@protocol P<NSObject>
{

-(void)foo;

@optional

-(void)bar;

}

And I have bunch of classes (let say a dozen). All of these classes implement protocol P. About half of them implement method bar and all of bar implementations are exactly the same.

What is the best way to share implementation of bar?

Obvious ideas:

1) Create some base class which will implement method bar and let other classes to inherit it.

It's simple to implement. However, I am not big fan of this idea. I prefer class hierarchy to represent entity generalization/specification rather than code reuse.

2) Create a helper and call it from all of classes which needs to implement bar method

Ok. It works. However, if implementation of bar is small (couple of lines in my case) then we will have more overhead (helper class and calling it from each class) than the code itself.

Is there any other (better) methods?

Victor Ronin
  • 22,758
  • 18
  • 92
  • 184

1 Answers1

4

Here are a few ways to share method implementations between classes:

  1. Inheritance. You can make all your classes inherit from a common base class that implements the shared methods. But you can't do this if, for example, you need class A to inherit from UIViewController and class B to inherit from NSManagedObject.

  2. Create a category on a base class shared by all your classes. For example, NSObject is the base class of (virtually) every other class. You can create a category on NSObject to add methods that all classes inherit. If you do this, you should put a prefix your method names to ensure that they won't conflict with other names. E.g. use ronin_foo and ronin_bar instead of just foo and bar.

  3. Create a file containing the method implementations, not surrounded by an @implementation block. Then #include this file in the middle of the @implementation block of each class that needs the methods. Note that the compiler will generate a copy of the machine code for each class, so this could make your program substantially bigger.

  4. At runtime, use the Objective-C runtime API to copy methods from one class to another. You will need to read the Objective-C Runtime Programming Guide and parts of the Objective-C Runtime Reference. You will probably also need to google up some examples.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • +1 #4 is a great answer, tricky though. I almost got it on my own, but ended up borrowing the `method_getImplementation()` from Larson's answer: http://stackoverflow.com/a/1638940/1218605 to actually transfer the guts of the method. This is me getting it to work, with files listed in a gist: https://gist.github.com/C4Framework/7228100 – C4 - Travis Oct 30 '13 at 07:04