Reputation: 6049
The previous instructions in the book that I am reading were to create a designated initializer for the BNRItem class, which the book walked me through:
BNRItem.h
// Designated initializer for BNRItem
- (instancetype)initWithItemName:(NSString *)name
valueInDollars:(int)value
serialNumber:(NSString *)sNumber;
BNRItem.m
- (instancetype)initWithItemName:(NSString *)name
valueInDollars:(int)value
serialNumber:(NSString *)sNumber {
// Call the superclass's designated initializer
self = [super init];
// Did the superclass's designated initializer succeed?
if (self) {
// Give the instance variables initial values
_itemName = name;
_serialNumber = sNumber;
_valueInDollars = value;
// Set _dateCreated to the current date and time
_dateCreated = [[NSDate alloc] init];
}
// Return the address of the newly created initialized object
return self;
}
The book also explained the init method that gets inherited from BRNItem's superclass and how to override the method:
BNRItem.h
-(instancetype)init {
return [self initWithItemName:@""];
}
Now, I am completing the challenge at the end of the chapter and I have a feeling that I am making this more complicated than it needs to be. The challenge reads:
"Create another initializer method for the BNRItem class. This initializer is not the designated initializer of BNRItem. It takes an instance of NSString that identifies the itemName of the item and an instance of NSString that identifies the serialNumber."
Below is the code that I have created:
BNRItem.h
// Another initializer
- (instancetype)initWithItemName:(NSString *)name
serialNumber:(NSString *)sNumber;
BNRItem.m
- (instancetype)initwithItemName:(NSString *)name
serialNumber:(NSString *)sNumber {
return [self initwithItemName:name
serialNumber:@""];
Is my solution correct?
Upvotes: 1
Views: 174
Reputation: 11514
Please try this one, you can call the Designated initializer in your init method.
- (instancetype)initWithItemName:(NSString *)name
serialNumber:(NSString *)sNumber {
// call the Designated initializer here
return [self initWithItemName:name
valueInDollars:0 //It is a default value
serialNumber:sNumber];
}
Upvotes: 2
Reputation: 28786
We nominate a designated initializer to extend from the super-class, and all other intializers call this designated initializer. The purpose of a designated initializer is:
If it makes sense we can have the designated initializer be private (by removing it from the header) and only expose simpler initializers. Eg when some of the parameters might be nil, rather than have the user guess if this is valid or not, we can provide an initializer with just the parameters for that usage.
All of your non-designated initializers will call the designated initializer. The designated initializer should expose the configurable parameters for all cases.
Upvotes: 2