Search code examples
objective-ciossubclassing

Subclassing and "promote" objects


I have a classes:

BasicObject : NSObject

AdvObject : BasicObject

in other class i make an instance by:

BasicObject *bObj = [[BasicObject alloc] initWithSomething:propertyOne andSomethingElse:propertyTwo];

BasicObject have two properties:

@interface BasicObject : NSObject

-(id)initWithSomething:propertyOne andSomethingElse:propertyTwo;

@property (strong,nonatomic) NSString* propertyOne;
@property (strong,nonatomic) NSArray* propertyTwo;

And then in initializer:

-(id)initWithSomething:propertyOne andSomethingElse:propertyTwo
{
    if (self = [super init])
    {
        _propertyOne = propertyOne;
        _propertyTwo = propertyTwo;

        if(!propertyTwo) //this is not valid condition i know, not important here
          {
             AdvObject *aObj = [[AdvObject alloc] initWithBasic:self]; //here it what i'm more concern about
             return aObj;
          }
    }

    return self;
}

So there in AdvObject class in initializer i have:

@implementation AdvObject

@synthesize basics = _basics;


-(id)initWithBasic:(BasicObject *)bObj
{
    if(self = [super init]) {
        _basics = bObj;
    }

    return self;
}

And after that when i return this object of course i have a object.basics filled properly, but why i can't access object.propertyOne? (this is nil). What i'm doing wrong? Is this a right design?


Solution

  • Or, you could avoid this entire pattern as being overly clever and create a class factory method that returns either a BasicObject or an AdvObject depending on the parameters that were passed to it.