Where does the init override go?


#1

It’s a pretty basic thing, but I have tried a few different ways and end up with syntax errors.

I don’t see page numbers in the Kindle version, but near Figure 2.14 (Initializer chain), there are instructions as follows:

“In BNRItem.m, override the init method to call the designated initializer with default values for all of the arguments.” Here’s the code the book calls for, but doesn’t show it in context of the code that is already there in BNRItem.m.

- (id) init
{
     return [self initWithItemName:@"Item"
                                valueInDollars:0
                                 serialNumber:@""];
}

Where is this code supposed to go in BNRItem.m? I’ve tried to insert it in a couple places, but I get syntax errors. Thanks!


#2

What are the syntax errors saying?


#3

Isn’t there some universal law that says as soon as you ask someone to help you with a problem, the problem goes away? I tried to reproduce the error and couldn’t. I inserted the code into the top of the BNRItem implementation file, and got no complaints from Xcode. Thanks for that. :slight_smile:

//
//  BNRItem.m
//  RandomPossessions
//
//  Created by Well-Tempered on 9/9/12.
//  Copyright (c) 2012 Well-Tempered. All rights reserved.
//

#import "BNRItem.h"

@implementation BNRItem

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

 {
    // Call the superclass's designate initializer
    self = [super init];
    
    // Did the superclass's designated initializer succeed?
    
    if (self) {
        
    
    // Give the instance variables initial values
    
    [self setItemName:name];
    [self setSerialNumber:sNumber];
    [self setValueInDollars:value];
    dateCreated = [[NSDate alloc]init];
    }
    
    // Return the address of the newly initialized object
    return self;
}


- (void)setItemName:(NSString *)str
{
    itemName = str;
}

- (NSString *)itemName
{
    return itemName;
}

- (void)setSerialNumber:(NSString *)str
{
    serialNumber = str;
}

- (NSString *)serialNumber
{
    return serialNumber;
}

- (void)setValueInDollars:(int)i
{
    valueInDollars = i;
}

- (int)valueInDollars
{
    return valueInDollars;
}

- (NSDate *)dateCreated
{
    return dateCreated;
}

- (NSString *)description
{
    NSString *descriptionString = [[NSString alloc] initWithFormat:@"%@ (%@): Worth $%d, recorded on %@", itemName, serialNumber, valueInDollars, dateCreated];
    return descriptionString;
}
@end