My challenge solution (Portfolio of Stocks & Foreign Stocks)


#1

Here’s my challenge solution. Let me know of any critiques/missteps/improvements. One of the things that occurred to me is that since ForeignStockHolding inherits from StockHolding, it is kind of a StockHolding also. So I could create both an instance of a StockHolding and ForeignStockHolding and pass them to a single Portfolio array to later be totalled in value by looping for every instance of a StockHolding in the array. Wonder if this makes sense or I’m totally off? :confused: . It does seem to give me the right answer.

Here is my code:

Portfolio.h

#import <Foundation/Foundation.h>
#import "StockHolding.h"

@interface Portfolio : NSObject
{
    NSString *portFolioName;
    NSMutableArray *stockPortfolio;
}

@property (strong) NSString *portFolioName;

-(void) addStocksToPortfolio: (StockHolding *) s; 
-(float) valueOfPortFolio;

@end

Portfolio.m

#import "Portfolio.h"

@implementation Portfolio

@synthesize portFolioName;

-(void) addStocksToPortfolio:(StockHolding *)p
{
    if (!stockPortfolio){
        stockPortfolio = [[NSMutableArray alloc]init];
    }
    [stockPortfolio addObject:p];
}

-(float) valueOfPortFolio{
    float sum =0;

    for (StockHolding *i in stockPortfolio){
        sum += [i valueInDollars];
    }

    return sum;
}

@end

main.m

#import <Foundation/Foundation.h>
#import "ForeignStockHolding.h"
#import "Portfolio.h"


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

    @autoreleasepool {
        //create 2 stock holdings amd 2 foreign stock holdings and add them to an array
        NSMutableArray *portfolioArr = [[NSMutableArray alloc]init];
        for(int i=1;i<3;i++){
            StockHolding *stocks = [[StockHolding alloc]init];
            [stocks setNumberOfShares:i*10];
            [stocks setCurrentSharePrice:i*1.2];
            [portfolioArr addObject:stocks];
            
            ForeignStockHolding *fStocks = [[ForeignStockHolding alloc]init];
            [fStocks setNumberOfShares:i*10];
            [fStocks setCurrentSharePrice:i*1.1];
            [fStocks setConversionRate:2.0];
            [portfolioArr addObject:fStocks];
        }
        
        //Create a Portfolio to add these objects
        Portfolio *johnsPortfolio = [[Portfolio alloc]init];
        [johnsPortfolio setPortFolioName:@"John's PortFolio"];
        for(StockHolding *s in portfolioArr){
            [johnsPortfolio addStocksToPortfolio:s];
        }
        NSLog(@"The value of %@ is $%0.2f",[johnsPortfolio portFolioName],[johnsPortfolio valueOfPortFolio]);
        
    }
    return 0;
}