0

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;
}
Community
  • 1
  • 1
Snowcrash
  • 80,579
  • 89
  • 266
  • 376

3 Answers3

2

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;
kean
  • 1,561
  • 14
  • 22
  • 1
    Given the answers are all much the same I'm picking this one as it mentioned the NS_DESIGNATED_INITIALIZER. – Snowcrash Feb 26 '15 at 10:56
0

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;
}
holex
  • 23,961
  • 7
  • 62
  • 76
0

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.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306