Is it acceptable/safe in Objective-C/Cocoa to wrapping the init
method as follows:
-(id)init {
if ((self=[super init])) {
self.bar = [[Bar alloc] init];
}
return self;
}
-(id)initWithFoo:(Foo *)f {
if ((self=[self init])) {
self.foo = f;
}
return self;
}
Note the [self init]
in initWithFoo
.
perhaps this is a simple yes answer... seem obvious, but not standard?
It's certainly acceptable and safe. I'm not certain if it's standard practice, but I don't think it's bad practice.
Note: This is not overloading. Overloading refers to a very specific thing in C-like languages (particularly C++) where you have multiple functions with the same name, distinguished only by their numbers and/or types of parameters. A better term for this would probably be something like forwarding or wrapping.
I know I'm late to the party but I thought I'd add my two cents.
If you provide both an init (which you definitely will do) and an initWithBlah then you'd be best doing something like this...
- (id)initWithValue:(int)value
{
self = [super init];
if (self) {
self.value = value;
}
return self;
}
- (id)init
{
int defaultValue = 10;
return [self initWithValue:defaultValue];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With