gpt4 book ai didi

objective-c - 子类化和 "promote"对象

转载 作者:行者123 更新时间:2023-11-28 22:53:55 25 4
gpt4 key购买 nike

我有一个类:

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? (这是零)。我做错了什么?这是正确的设计吗?

最佳答案

或者,您可以避免整个模式过于聪明,并创建一个类工厂方法,根据传递的参数返回 BasicObjectAdvObject

关于objective-c - 子类化和 "promote"对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11207567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com