Jack Woodruff
Jack Woodruff

Reputation: 11

What is the Purpose of Multiple Initializers

I understand the purpose of having an initializer is to set the instance variables to certain values. However, I am confused as to why you would want to have multiple initializers for each instance variable. Can't one initializer set all the instance variables? I guess my question really is what is the practicality of having multiple initializers in a class. For instance a class has the following:

    - (id)initWithItemName:(NSString *)name
    {
    return [self initWithItemName:name valueInDollars:0 serialNumber:@""];
    }

Meanwhile the designated initializer is given as such:

    - (id) initWithItemName:(NSString *)name valueInDollars:(int)value 
                                     serialNumber:(NSString *)sNumber; 

The designated initializer, as you can see, already initializes the itemName variable. So, whats the pont of having a specific initializer just for one variable.

Upvotes: 1

Views: 96

Answers (1)

blake305
blake305

Reputation: 2236

  • Default values. If you use the designated initializer with a default value that you have to specify each time, it can be a pain if you want to change this default value because you would have to go to every instance of this initializer and change the value. If you have an initializer that centralizes the location of the default value, it's easy to change.
  • Deprecation. If you have to add a variable to the class and to the initializer later on, then it's much easier to not have to change every place that initializes the variable when you don't need to specify a value.

Upvotes: 1

Related Questions