Chapter Challenge -- Great Exercise


#1

main

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

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

@autoreleasepool {
    
    //create a Portfolio object, allocate space in memory, initialize and set ID
    Portfolio *myPortfolio = [[Portfolio alloc]init];
    [myPortfolio setPortfolioID: 100];
    
    for(int i = 0; i < 10; i++)
    {
        StockHolding *theStock = [[StockHolding alloc]init];
        
        [theStock setNumberOfShares:325];
        [theStock setPurchaseSharePrice:(i * 100) - (50 - i)];
        [theStock setCurrentSharePrice:(20 * i) + 100];
        
        [myPortfolio addStockObject];
        
       
    }
    
    int totalValue = [myPortfolio valueOfStocks];
    NSLog(@"\nPortfolio ID: %i\nThe total value of the portfolio is: $%.2d", [myPortfolio portfolioID], totalValue);

}
return 0;

}


header

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

@interface Portfolio : NSObject
{
int portfolioID;
NSMutableArray *stocks;
}
@property int portfolioID;
-(void)addStockObject:(StockHolding *)s;
-(unsigned int) valueOfStocks;

@end


Implementation

#import “Portfolio.h”
#import “StockHolding.h”

@implementation Portfolio

@synthesize portfolioID;
-(void)addStockObject:(StockHolding *)s
{

//if stocks array doesn't exist, create it
if(!stocks)
{
    //create the array
    stocks = [[NSMutableArray alloc]init];
    
}
//if it does exist, add this object to the array
[stocks addObject:s];

}

-(unsigned int) valueOfStocks
{
//sum the total stocks
unsigned int sum = 0;
for(StockHolding *s in stocks){
sum+=[s valueInDollars];
}

return sum;

}

@end