Snowcrash
Snowcrash

Reputation: 86097

Objective-C: Why not call the designated initializer?

I've inherited this code:

- (id)initWithLocation:(CLLocation *)inLocation {
    if (self = [super init])
    {
        _location = [inLocation copy];
    }
    return self;
}

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset {
    if (self = [super init])
    {
        _location = [inLocation copy];
        _offset = [offset copy];
    }
    return self;
}

and am wondering if there's a good reason why the first method does not call the designated initializer (e.g. like this Is it okay to call an init method in self, in an init method?)?

i.e. why not do this:

- (id)initWithLocation:(CLLocation *)inLocation {
    if (self = [super init])
    {
        [self initWithLocation:inLocation offsetValue:nil];
    }
    return self;
}

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset {
    if (self = [super init])
    {
        _location = [inLocation copy];
        _offset = [offset copy];
    }
    return self;
}

Upvotes: 0

Views: 54

Answers (3)

kean
kean

Reputation: 1561

The - (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset method should be a designated initializer and the - (id)initWithLocation:(CLLocation *)inLocation should call it like this:

- (id)initWithLocation:(CLLocation *)inLocation {
    return [self initWithLocation:inLocation offsetValue:nil];
}

It's also considered a good practice to mark a designated initializer in the class interface using NS_DESIGNATED_INITIALIZER:

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset NS_DESIGNATED_INITIALIZER;

Upvotes: 2

Fogmeister
Fogmeister

Reputation: 77641

All you actually need to do is...

- (id)initWithLocation:(CLLocation *)inLocation {
    return [self initWithLocation:inLocation offsetValue:nil];
}

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset {
    if (self = [super init])
    {
        _location = [inLocation copy];
        _offset = [offset copy];
    }
    return self;
}

And you're right. There is no reason not to in this case.

Upvotes: 0

holex
holex

Reputation: 24041

the much more appropriate way would be like this:

- (id)initWithLocation:(CLLocation *)inLocation {
    return [self initWithLocation:inLocation offsetValue:nil];
}

- (id)initWithLocation:(CLLocation *)inLocation offsetValue:(NSNumber *)offset {
    if (self = [super init]) {
        _location = [inLocation copy];
        _offset = [offset copy];
    }
    return self;
}

Upvotes: 0

Related Questions