[英]Setting properties defined in a super class in the initialiser
From what I learned a general rule of thumb setting values in init
is a matter of using the ivars directly. 从我了解到的经验来看,在init
设置值的一般规则是直接使用ivars。
For example 例如
@interface CustomClass
@property (nonatomic, strong) NSString *name;
@end
and then: 接着:
- (instancetype)initWithName:(NSString *)name
{
if (self = [super init]) {
_name = name;
}
return self;
}
Now so far so good. 现在到目前为止一切顺利。 I'm interested in a slightly different case. 我对一个稍微不同的情况感兴趣。 Let's say you're subclassing a UIView and in the initialiser you want to assign a background color to that subclass. 假设您要对UIView进行子类化,并在初始化程序中要为该子类分配背景色。 Here, the property backgroundColor
is defined in the parent class. 在这里,属性backgroundColor
是在父类中定义的。 My question is: Is it bad style or potentially wrong to use self
in the initialiser? 我的问题是:在初始化程序中使用self
是不好的风格还是潜在的错误? Would it be better to set the background color somewhere else? 在其他地方设置背景颜色会更好吗?
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor greenColor];
}
return self;
}
I believe it is perfectly fine what you are doing there. 我相信您在那里所做的一切都很好。 At that point, after calling super.init
, the self
exists, and you can use it (you are calling return self
, too, so why would other references to self
be wrong?). 那时,在调用super.init
,该self
存在,并且可以使用它(您也正在调用return self
,所以为什么其他对self
引用会出错?)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.