Reputation: 1916
From what I learned a general rule of thumb setting values in init
is a matter of using the ivars directly.
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. Here, the property backgroundColor
is defined in the parent class. My question is: Is it bad style or potentially wrong to use self
in the initialiser? 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;
}
Upvotes: 2
Views: 33
Reputation: 19737
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?).
Upvotes: 3