My Solution to the Challenge


#1

One thing I took into consideration is that the value in dollars of the holdings in the portfolio are obtained in different ways. To accommodate this I separated domestic stocks from foreign stocks.

Portfolio.h

[code]#import <Foundation/Foundation.h>
@class StockHolding;
@class ForeignStockHolding;

@interface Portfolio : NSObject
{
NSMutableArray *domesticStocks;
NSMutableArray *foreignStocks;
}

  • (void)addDomesticStocks:(StockHolding *)d;
  • (void)addForeignStocks:(ForeignStockHolding *)f;
  • (float)currentValue;
    @end[/code]

Portfolio.m

[code]#import “Portfolio.h”
#import “StockHolding.h”
#import “ForeignStockHolding.h”

@implementation Portfolio

  • (void)addDomesticStocks:(StockHolding *)d {
    if (!domesticStocks) {
    domesticStocks = [[NSMutableArray alloc] init];
    }
    [domesticStocks addObject:d];
    }

  • (void)addForeignStocks:(ForeignStockHolding *)f {
    if (!foreignStocks) {
    foreignStocks = [[NSMutableArray alloc] init];
    }
    [foreignStocks addObject:f];
    }

  • (float)currentValue {
    float value = 0;
    //iterate through domestic stocks
    for (StockHolding *stocks in domesticStocks) {
    value += [stocks valueInDollars];
    }

    //iterate through foreign stocks
    for (ForeignStockHolding *foreigns in foreignStocks) {
    value += [foreigns valueInDollars];
    }

    return value;
    }
    @end[/code]

I didn’t get fancy with the output in the main class, just output the portfolio value.
main.m

[code]#import <Foundation/Foundation.h>
#import “ForeignStockHolding.h”
#import “Portfolio.h”

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

@autoreleasepool {
    
    Portfolio *portfolio = [[Portfolio alloc] init];
    ForeignStockHolding *stock1 = [[ForeignStockHolding alloc] init];
    [stock1 setNumberOfShares:2];
    [stock1 setCurrentSharePrice:10.0];
    [stock1 setPurchaseSharePrice:5.0];
    [stock1 setConversionRate:1.4];
    [portfolio addForeignStocks:stock1];
    
    ForeignStockHolding *stock2 = [[ForeignStockHolding alloc] init];
    [stock2 setNumberOfShares:50];
    [stock2 setCurrentSharePrice:100.0];
    [stock2 setPurchaseSharePrice:50.0];
    [stock2 setConversionRate:2.6];
    [portfolio addForeignStocks:stock2];
    
    StockHolding *stock3 = [[StockHolding alloc] init];
    [stock3 setNumberOfShares:34];
    [stock3 setCurrentSharePrice:15.5];
    [stock3 setPurchaseSharePrice:11.0];
    [portfolio addDomesticStocks:stock3];
    
    NSLog(@"The current value of the portfolio is $%.2f", [portfolio currentValue]);
}
return 0;

}[/code]