1

I've been programming in Objective-C for years now, and I always bump into this problem: If you have an object with multiple initializers, but there is code in common to all of them, how do you extract it out?

The best I've been able to come up with is something like this:

@implementation Example

- (void)privateInitWithString:(NSString*)aString
{
  self.str = aString;
}

- (id)init
{
  self = [super initWithWindowNibName:@"MyNib"]
  if(self) {
    [self privateInitWithString:@""];
  }
  return self;
}

- (id)initWithString:(NSString*)aString
{
  self = [super initWithWindowNibName:@"MyNib"]
  if(self) {
    [self privateInitWithString:aString];
  }
  return self;
}

@end

There is a lot of duplication in the individual initializers which a code smell. However I can't think of a way to get one initializer to "fall through" to another one because there is no guarantee that self has been set before calling [super init]

Is there a best practice for this that I'm missing?

1 Answer 1

4

You write one "designated initialiser". That initialiser handles all the different situations. In your case, initWithString seems a good candidate. And init just becomes

- (instancetype)init { return [self initWithString:@""]; }

You can read more about it here:

https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/Initialization/Initialization.html

Sign up to request clarification or add additional context in comments.

2 Comments

+1 the technically correct answer, although there are a couple of scenarios where you can have multiple designated initializers, such as if you make your class conform to <NSCoding> (or sometimes <NSCopying>).
That's perfect! Here's a link to the section titled "Multiple Initializers and the Designated Initializer" at the bottom of the page: developer.apple.com/library/ios/documentation/general/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.