Chapter 17 Challenge Solution


#1

// main.m

// Declare objects(three instances of StockHolding class
StockHolding *firstStockHolding = [[StockHolding alloc] init];
StockHolding *secondStockHolding = [[StockHolding alloc] init];
StockHolding *thirdStockHolding = [[StockHolding alloc] init];

    // Assign values to each object in a secure & private way
    [firstStockHolding setPurchaseSharePrice:2.30];
    [firstStockHolding setCurrentSharePrice:4.50];
    [firstStockHolding setNumberOfShares:40];
    
    [secondStockHolding setPurchaseSharePrice:12.19];
    [secondStockHolding setCurrentSharePrice:10.56];
    [secondStockHolding setNumberOfShares:90];
    
    [thirdStockHolding setPurchaseSharePrice:45.10];
    [thirdStockHolding setCurrentSharePrice:49.51];
    [thirdStockHolding setNumberOfShares:210];
    
    // Create an instance of NSMutableArray
    NSMutableArray *listOfStock = [NSMutableArray array];
    
    // Fill the array
    [listOfStock addObject:firstStockHolding];
    [listOfStock addObject:secondStockHolding];
    [listOfStock addObject:thirdStockHolding];
    
    // Iterate through the array printing out the value of each
    for (StockHolding *stock in listOfStock) {
        NSLog(@"Purchase Share Price: %.2f , Current Share Price: %.2f , Number Of Share: %d , Cost In Dollars: %.2f , Value In Dollars:  , %.2f", [stock purchaseSharePrice], [stock currentSharePrice], [stock numberOfShares], [stock costInDollars], [stock valueInDollars]);
    }

// StockHolding.h
@interface StockHolding : NSObject
// Three instance variables
{
float purchaseSharePrice;
float currentSharePrice;
int numberOfShares;
}

@property float purchaseSharePrice;
@property float currentSharePrice;
@property int numberOfShares;

// Instance methods

  • (float)costInDollars;
  • (float)valueInDollars;

@end

// StockHolding.m
@implementation StockHolding

@synthesize purchaseSharePrice;
@synthesize currentSharePrice;
@synthesize numberOfShares;

  • (float)costInDollars
    {
    return [self purchaseSharePrice] * [self numberOfShares];
    }

  • (float)valueInDollars
    {
    return [self currentSharePrice] * [self numberOfShares];
    }

@end