I've been using Objective-C for a few years, but I'm still unsure how to initialize an object. Our problem is this:
-(id)init {
self = [super init];
if (self) {
self.backgroundColor = [UIColor blueColor];
self.textColor = [UIColor greenColor];
}
return self;
}
-(id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor yellowColor];
}
return self;
}
Getting it to be initialized the same in both methods means either copy and paste coding (huge no-no, causes endless problems due to human error, such as values being different, like in the example above) or a new method:
-(id)init {
self = [super init];
if (self) {
[self initialSetup];
}
return self;
}
-(id)initialSetup {
self.backgroundColor = [UIColor blueColor];
self.textColor = [UIColor greenColor];
}
This then has the problem that if a subclass has an initialSetup
method, the superclass calling [self initialSetup]
will call the subclass's initialSetup
, and thus ignore all of the superclass's setup. You can get around this by appending the class name each time, such as initialSetupTextField
.
This seems rather messy though. This is all just to initialize an object. How does everyone else do this?