# 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];

}

int totalValue = [myPortfolio valueOfStocks];
NSLog(@"\nPortfolio ID: %i\nThe total value of the portfolio is: \$%.2d", [myPortfolio portfolioID], totalValue);

}
return 0;
``````

}

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

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

@end

Implementation

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

@implementation Portfolio

@synthesize portfolioID;
{

``````//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
``````

}

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

``````return sum;
``````

}

@end