0

我有一堂课:

BasicObject : NSObject

AdvObject : BasicObject

在其他类中,我通过以下方式创建一个实例:

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

BasicObject 有两个属性:

@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

或者,您可以避免整个模式过于聪明,并创建一个根据传递给它的参数返回 aBasicObject或 an的类工厂方法。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 回答