tags:

views:

75

answers:

4

I have multiple classes (controllers) that share a huge chunk of code with each other. How can I factor out this piece of code? The code is some methods that belong to a protocol. In other words, all my controllers are behaving the same way with regards to this protocol. I can't make them subclasses of the same parent because they are already subclasses of some different controllers.

+2  A: 

Use aggregation :) Build a single reusable class that conforms to the protocol, and delegate to it.

slf
+1 -- this is exactly what delegation is for.
Meredith L. Patterson
Not entirely; delegation is for when you want to centralize control decisions in one spot or in something outside of the class hierarchy. As the question reads, this sounds much more like it would be solved with straightforward inheritance.
bbum
A: 

You can have Multiple Inheritance sort of, make them "inherit" from some super class that implements the protocol...http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtForwarding.html talks about it

Daniel
+1  A: 

Make an abstract superclass from which all of your generic controller classes inherit. That abstract super can implement the protocol(s) needed and the relatively generic or very specific sub or sub-sub classes can override.

Consider the various views/responders in the iPhone SDK.

The UIResponder class offers event handling.

UIView subclasses to add drawing functionality.

UIControl subclasses UIView to add various control like behavior.

Then there is UIButton, UITextField, UISlider, etc... all of which subclass UIControl to add their specific functionality.

If you look carefully, the NSCoding (and NSObject) protocols are declared as supported by various classes in the hierarchy and the more specific subclasses override, as needed.

bbum
+1  A: 

Add a category to a common superclass (NSObject, if necessary).

Kristopher Johnson