Objective C - creating concrete class instances from base class depending upon type

Posted by indiantroy on Stack Overflow See other posts from Stack Overflow or by indiantroy
Published on 2012-07-03T21:00:08Z Indexed on 2012/07/03 21:15 UTC
Read the original article Hit count: 145

Filed under:
|
|

Just to give a real world example, say the base class is Vehicle and concrete classes are TwoWheeler and FourWheeler. Now the type of the vehicle - TwoWheeler or FourWheeler, is decided by the base class Vehicle. When I create an instance of TwoWheeler/FourWheeler using alloc-init method, it calls the super implementation like below to set the value of common properties defined in the Vehicle class and out of these properties one of them is type that actually decides if the type is TwoWheeler or FourWheeler.

   if (self = [super initWithDictionary:dict]){
     [self setOtherAttributes:dict]; 
      return self; 
    }

Now when I get a collection of vehicles some of them could be TwoWheeler and others will be FourWheeler. Hence I cannot directly create an instance of TwoWheeler or FourWheeler like this

Vehicle *v = [[TwoWheeler alloc] initWithDictionary:dict];

Is there any way I can create an instance of base class and once I know the type, create an instance of child class depending upon type and return it. With the current implementation, it would result in infinite loop because I call super implementation from concrete class.

What would be the perfect design to handle this scenario when I don't know which concrete class should be instantiated beforehand?

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about ios