How does class composition work in iOS?

前端 未结 2 1273
走了就别回头了
走了就别回头了 2021-01-01 13:41

Let\'s say I have property A on classA and property B on classB and I want classAB to have both properties <

2条回答
  •  独厮守ぢ
    2021-01-01 14:22

    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;
    }
    

提交回复
热议问题