20

Let's say I have property A on classA and property B on classB and I want classAB to have both properties A and B. I still don't understand how to make this all work with composition.

I realize this can be done with inheritance, but I want to learn how to do this with composition. I've looked at examples and I still don't get how it all works.

2 Answers 2

21

You make a new class, which has instances of classA and classB as member variables. Then you implement the properties by passing through the get/set methods.

@interface ClassAB
{
    ClassA *objectA;
    ClassB *objectB;
}
@property (nonatomic,strong) id propertyA;
@property (nonatomic,strong) id propertyB;
@end

@implementation ClassAB
- (id)propertyA { return objectA.propertyA; }
- (void)setPropertyA:(id)value { objectA.propertyA = value; }
- (id)propertyB { return objectB.propertyB; }
- (void)setPropertyB:(id)value { objectB.propertyB = value; }
@end

And that's what composition is. Some languages have special syntax to do this (e.g., in Ruby you can include a set of methods from one class/module in another), but Objective-C doesn't allow this.

One thing you can do in Objective-C is catch messages sent to your object which do not have an associated method, and forward them to another object. This trick is useful if you are writing a class that will pose as another class, or if there are many different messages to forward and you don't want to write them all out manually.

The downside to using message forwarding is that you give up some control and it can be a harder to predict when a message will be handled by your class or the forwarding class. For example, if a superclass implements a method, that method will be executed and the forwarding code will not be called.

4
  • @Jackson before you accept this answer, let me write up something with KVO that will let you do this in a more elegant way. Mar 14, 2012 at 21:26
  • 2
    I believe this to be the better solution for readability. Richards solution is a neat trick but I always place pragmatism and readability over tricky code. Matter of style I guess
    – Slappy
    Mar 14, 2012 at 22:04
  • @Slappy I've used what is essentially Richard's approach on exactly one occasion — when I had existing code that I couldn't modify to which I had to pass an NSString (which is a class cluster and so subclassing it isn't trivial) to which I wanted to a sideband of communications. The runtime's associated objects were the main alternative approach considered but I felt the forwardingTargetForSelector: (albeit to create a pretend subclass rather than to compose in my case) was the cleaner and more readable solution.
    – Tommy
    Mar 14, 2012 at 23:01
  • 1
    This is a good answer, but I would add three minor points for completeness, especially for novices: 1) make sure the properties you want to access in ClassA and ClassB are exposed in the header files, and 2) you have to alloc init ClassA and ClassB in ClassAB in either ViewDidLoad or in your init routine, and 3) You have to #import "ClassA.h" and "ClassB.h" into ClassAB.m.
    – SmileBot
    Apr 18, 2013 at 13:29
8

Assuming ClassA and ClassB are implemented as you said, this works very well, and is easily extendable.

@interface ClassAB : NSObject

@property int a;
@property int b;

@property ClassA *aObject;
@property ClassB *bObject;

@end

@implementation ClassAB

@dynamic a, b;
@synthesize aObject, bObject;

-(id) forwardingTargetForSelector:(SEL)aSelector
{
    if ([aObject respondsToSelector:aSelector])
        return aObject;
    else if ([bObject respondsToSelector:aSelector])
        return bObject;

    return nil;    
}

@end

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        ClassA *a = [ClassA new];
        ClassB *b = [ClassB new];

        ClassAB *ab = [ClassAB new];
        ab.aObject = a;
        ab.bObject = b;

        ab.a = 10;
        ab.b = 20;

        NSLog(@"%i, %i", a.a, b.b); // outputs 10, 20
    }
    return 0;
}
5
  • Oh, Richard J. Ross III, how is it that you so often post my thoughts just before I do so? Usually I notice in time to avoid hitting the button... might be worth making the explicit point that if you cast ab to type ClassA then it'd behave exactly like a real instance of ClassA for all defined methods and properties and if you cast it to ClassB it'd behave the same for all defined methods and properties that aren't also defined by ClassA?
    – Tommy
    Mar 14, 2012 at 21:37
  • @Tommy it must be my ninja senses :) Mar 14, 2012 at 21:40
  • @Tommy that is actually incorrect if ClassAB implements a selector that ClassA does as well, in which case the ClassAB implementation will be called (For Example, a custom -description implementation). Mar 14, 2012 at 21:41
  • Yep, incorrect under those circumstances but entirely correct for ab as in your example.
    – Tommy
    Mar 14, 2012 at 22:57
  • 1
    @Tommy I'm not sure I understand what you guys are saying, but Objective-C only uses object types for compile-time checking. Casting a pointer from one type to another won't affect how the object will behave; that information is lost at run-time.
    – benzado
    Mar 15, 2012 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.