我有一个课程:
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? (这是零)。我做错了什么?这是一个正确的设计吗?
答案 0 :(得分:2)
或者,您可以避免将整个模式过于聪明,并创建一个类工厂方法,该方法返回BasicObject
或AdvObject
,具体取决于传递给它的参数。
答案 1 :(得分: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,因此您需要仔细测试。