Using Initializers


#1

hello,
in Chapter 2 I overriden the init method in BRNItem like you say:

#import “BNRItem.h”
@implementation BNRItem

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

  • (id)initWithItemName:(NSString *)name
    valueInDollars:(int)value
    serialNumber:(NSString *)sNumber
    {

    // call the super class’s designated initializer
    self =[super init];

    if (self) {
    // Give the istance 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;

}

in main.m :

#import <Foundation/Foundation.h>
#import “BNRItem.h”

int main(int argc, const char * argv[])
{

@autoreleasepool {
    BNRItem *p = [[BNRItem alloc] init];
    NSLog(@"%@", p); 
   
  // This creates a new NSString, "Red Sofa", and gives it to the BNRItem
 [p setItemName:@"Red Sofa"];

}
return 0;

}

What I get on the console is :

2012-06-09 10:58:16.449 RandomPossessions[23564:503] Item (): Worth $0, recorded on 2012-06-09 08:58:16 +0000

According to the example I would have two messages. The second one would be :
Red Sofa (A1B2C): Worth $100, recorded on recorded on 2012-06-09 08:58:16 +0000

Am I missing something ???
Thank you in advance!


#2

You are missing two statements.

After the statement [p setItemName:@“Red Sofa”], add these two statements:
[p setValueInDollars:100];
NSLog(@"%@", p);

By the way, there is a case error in one of the method names you are invoking; see if you can find it :slight_smile:


#3

Ibex10, I think there is something wrong;
if you take a look at Using Initializers paragraph you will not find any mention about adding the two statements you are talking about and another NSLog either.
May be there is an error in the book

P.S. Where is the case error?

Thank you :slight_smile:


#4

Sorry I should have said, in main (), after the statement [p setItemName:@“Red Sofa”], add these two statements:…

Because you have only one NSLog statement in your main, you are getting only one message on the console.

As for the case error, look in the method - (id)initWithItemName:(NSString *)name ….
[self [color=#FF0000]setvalueInDollars[/color]:value] should be [self setValueInDollars:value]


#5

Thank you !
Then I was right telling that there are errors in that page of the book.

Thank you again!