0

私はクラスを持っています:

BasicObject : NSObject

AdvObject : BasicObject

他のクラスでは、次の方法でインスタンスを作成します。

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

BasicObject には次の 2 つのプロパティがあります。

@interface BasicObject : NSObject

-(id)initWithSomething:propertyOne andSomethingElse:propertyTwo;

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

そして、初期化子で:

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

したがって、初期化子の AdvObject クラスには次のものがあります。

@implementation AdvObject

@synthesize basics = _basics;


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

    return self;
}

その後、もちろんこのオブジェクトを返すと、object.basics が適切に埋められますが、なぜ object.propertyOne にアクセスできないのでしょうか? (これはゼロです)。私が間違っているのは何ですか?これは正しい設計ですか?

4

2 に答える 2

2

または、このパターン全体が過度に巧妙であるのを避けて、渡されたパラメーターに応じてBasicObjectまたはを返すクラスファクトリメソッドを作成することもできます。AdvObject

于 2012-06-26T12:59:34.273 に答える
0

以下init...に示すように、メソッドはいくつかの異なることを行う必要があります。

- (id)initWithSomething:propertyOne andSomethingElse:propertyTwo
{
    if (self = [super init])
    {
        if (!propertyTwo)
        {
             self = [[AdvObject alloc] initWithBasic:self];
        }

        _propertyOne = propertyOne;
        _propertyTwo = propertyTwo;
    }

    return self;
}

私はこれを ARC で実際に試したことがないので、慎重にテストする必要があります。

于 2012-06-26T13:29:15.940 に答える