0

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];
}
AdamT
  • 6,405
  • 10
  • 49
  • 75

1 Answers1

0

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.

Community
  • 1
  • 1
jscs
  • 63,694
  • 13
  • 151
  • 195
  • A key rule that you should follow is that all extra initializers that you write should call the designated initializer. If a class has multiple initializers, the author of the class should label one of them as the "designated" initializers. All other initializers should call the designated initializer. That way you can do all the "heavy lifting" to initialize an object in the designated initializer, and other initializers just need to do anything extra. – Duncan C Jun 23 '12 at 22:49