Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `self = [self init]` to wrap other `init message`

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?

like image 268
Ross Avatar asked Nov 15 '12 19:11

Ross


2 Answers

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.

like image 96
Adam Rosenfield Avatar answered Oct 02 '22 00:10

Adam Rosenfield


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];
}
like image 22
Fogmeister Avatar answered Oct 01 '22 23:10

Fogmeister