When to use self?


#1

With ForeignStockHolding, I created a Chinese stockholder who buys shares in yen, which is converted to US dollars. Here’s how I set up my files at first:

.h

[code]#import “StockHolding.h”

@interface ForeignStockHolding : StockHolding

{
float conversionRate;

}

// Set the accessors
@property float conversionRate;

@end[/code]

.m

[code]#import “ForeignStockHolding.h”

@implementation ForeignStockHolding

@synthesize conversionRate;

  • (float)costInDollars
    {
    float yenCost = [super costInDollars];
    return yenCost * conversionRate;
    }

  • (float)valueInDollars
    {
    float yenValue = [super valueInDollars];
    return yenValue * conversionRate;
    }

@end[/code]

And here is how I created a Chinese stockholder in main()

// Create instance 2 of chinese StockHolding and assign values to instance variables ForeignStockHolding *xengbo = [[ForeignStockHolding alloc] init]; [xengbo setPurchaseSharePrice:10.30]; [xengbo setCurrentSharePrice:12.50]; [xengbo setNumberOfShares:40]; [xengbo setConversionRate:.94];

Unfortunately, when I printed out the cost and current value in US dollars of of this guy’s stock, it returned values of $0. Then I returned conversionRate to self in my .m file and it printed out the correct dollar values:

[code]#import “ForeignStockHolding.h”

@implementation ForeignStockHolding

@synthesize conversionRate;

  • (float)costInDollars
    {
    float yenCost = [super costInDollars];
    return yenCost * [self conversionRate];
    }

  • (float)valueInDollars
    {
    float yenValue = [super valueInDollars];
    return yenValue * [self conversionRate];
    }

@end[/code]

I’m a bit unclear on why the method conversionRate needs self because that method is unique to only ForeignStockHolding and therefore the program should know what object it’s pointing to. Why don’t all methods need self then?