My Solution To Challenge


#1

Going with the spirit of the last chapter, I tried to recycle the same pointer for both the instances of StockHolding and ForeignStockHolding. I believe this emulates the diagram 18.3:

[code]//
// ForeignStockHolding.h
// Stocks
//
// Created by William on 11/1/12.
// Copyright © 2012 MyCompanyName. All rights reserved.
//

#import “StockHolding.h”

@interface ForeignStockHolding : StockHolding
{
float converstionRate;
}
@property float conversionRate;

@end
[/code]

[code]//
// ForeignStockHolding.m
// Stocks
//
// Created by William on 11/1/12.
// Copyright © 2012 MyCompanyName. All rights reserved.
//

#import “ForeignStockHolding.h”

@implementation ForeignStockHolding

@synthesize conversionRate;

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

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

@end
[/code]

[code]//
// main.m
// Stocks
//
// Created by William on 10/30/12.
// Copyright © 2012 MyCompanyName. All rights reserved.
//

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

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

@autoreleasepool {
    
    // create an array instance
    NSMutableArray *portfolio = [[NSMutableArray alloc] init];
    
    // create pointer - to store either class or subclass object
    id stockholding;
    
    // ** DOMESTIC CURRENCY ** 
    // Use/Reuse Pointer, Setter Methods, Add to Array
    stockholding = [[StockHolding alloc] init];   
    [stockholding setPurchaseSharePrice:2.30];
    [stockholding setCurrentSharePrice:4.50];
    [stockholding setNumberOfShares:40];
    [portfolio addObject: stockholding];
    
    stockholding = [[StockHolding alloc] init];   
    [stockholding setPurchaseSharePrice:2.30];
    [stockholding setCurrentSharePrice:4.50];
    [stockholding setNumberOfShares:40];
    [portfolio addObject: stockholding];
    
    // ** FOREIGN CURRENCY **
    // Use/Reuse Pointer, Setter Methods, Add to Array
    stockholding = [[ForeignStockHolding alloc] init];
    [stockholding setPurchaseSharePrice:2.30];
    [stockholding setCurrentSharePrice:4.50];
    [stockholding setNumberOfShares:40];
    [stockholding setConversionRate:0.94];
    [portfolio addObject: stockholding];        
    
    // iterate thru the array and print values
    for (StockHolding *s in portfolio) {
        NSLog(@"Cost: %.2f, Value: %.2f",[s costInDollars], [s valueInDollars]);
    }
}
return 0;

}[/code]