Challenge 19 Solution


#1

Here’s my solution to this problem. I took the challenge to require Portfolio to do a little more work, so my answer reflects that. I’ve not included StockHolding.h & .m as I made no modifications to that class.

Portfolio.h

#import <Foundation/Foundation.h>
@class StockHolding;

@interface Portfolio : NSObject
{
    NSMutableArray *stocksHeld;
}

-(float)portfolioValue;

-(void)addStock:(StockHolding *)stock;

@end

Portfolio.m

@implementation Portfolio


-(void)addStock:(StockHolding *)stock
{
    // Check to see if stocksHeld is nil
    if (!stocksHeld) {
        stocksHeld = [[NSMutableArray alloc] init];
    }
    [stocksHeld addObject:stock];
}

-(float)portfolioValue
{
    float totalValue = 0;
    for (StockHolding *s in stocksHeld) {
        totalValue += [s valueInDollars];
    }
    return totalValue;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"The total portfolio is worth: $%.2f and is comprised of %ld stock(s)", [self portfolioValue], [stocksHeld count]];
}

@end

main.m

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

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

    @autoreleasepool {
        
        Portfolio *portfolio = [[Portfolio alloc] init];
        StockHolding *stocks = [[StockHolding alloc] init];
        
        [stocks setPurchaseSharePrice:2.3];
        [stocks setCurrentSharePrice:4.5];
        [stocks setNumberOfShares:40];
        
        [portfolio addStock:stocks];
        
        stocks = [[StockHolding alloc] init];
        
        [stocks setPurchaseSharePrice:12.19];
        [stocks setCurrentSharePrice:10.56];
        [stocks setNumberOfShares:90];
        
        [portfolio addStock:stocks];
        
        stocks = [[StockHolding alloc] init];
        
        [stocks setPurchaseSharePrice:45.10];
        [stocks setCurrentSharePrice:49.51];
        [stocks setNumberOfShares:210];
        
        [portfolio addStock:stocks];
        
        NSLog(@"%@", portfolio);
        
    }
    return 0;
}