The assignment in the Big Nerd Ranch Guide says:
Silver Challenge: Another initializer
Create another initializer method for BNRItem.
This initializer is not the designated initializer of BNRItem.
It takes an NSString that identifies the itemName of the item and an
NSString that identifies the serialNumber.
I’m not sure I’ve implemented it correctly. Is this correct?
BNRItem.h
- (id)initWithItemName:(NSString *)name
valueInDollars:(int)value
serialNumber:(NSString *)aNumber;
// I added this for new initializer
- (id)initWithItemName:(NSString *)name serialNumber:(NSString *)aNumber;
BNRItem.m
- (id)initWithItemName:(NSString *)name valueInDollars:(int)value serialNumber:(NSString *)aNumber
{
self = [super init];
if (self)
{
[self setItemName:name];
[self setSerialNumber:aNumber];
[self setValueInDollars:value];
dateCreated = [[NSDate alloc] init];
}
return self;
}
// Added the implementation for the new initializer
- (id) initWithItemName:(NSString *)name serialNumber:(NSString *)aNumber
{
return [self initWithItemName:name valueInDollars:0 serialNumber:aNumber];
}
Yes, you’ve got it. Well done!
The key point is the chaining of initializers, as described in the Cocoa Fundamentals Guide (and probably in the BNR book). Each non-designated initializer in a class should call the class’s designated initializer,* which should call the superclass’s DI.
Aside: some people (I’m one of them) will tell you not to use accessor methods in
init, but since you’re just learning, do what the book tells you. I provide this only as further reading material.*With the exception of
initWithCoder:, for any exacticians looking on.