Search Results

Search found 1 results on 1 pages for 'indiantroy'.

Page 1/1 | 1 

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

    - by indiantroy
    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?

    Read the article

1