Challenge 17 Solution


[code]#import <Foundation/Foundation.h>

@interface StockHolding : NSObject

float purchaseSharePrice;
float currentSharePrice;
int numberOfShares;

// The accessor methods for the three instance variables
@property float purchaseSharePrice;
@property float currentSharePrice;
@property int numberOfShares;

//Two other instance methods

  • (float)costInDollars; // purchaseSharePrice * numberOfShares
  • (float)valueInDollars;


[code]#import “StockHolding.h”

@implementation StockHolding

@synthesize purchaseSharePrice, currentSharePrice, numberOfShares;

  • (float)costInDollars
    return (purchaseSharePrice * numberOfShares);

  • (float)valueInDollars
    return (currentSharePrice * numberOfShares);


[code]#import <Foundation/Foundation.h>
#import “StockHolding.h”

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

@autoreleasepool {
    StockHolding *holder1 = [[StockHolding alloc] init];
    [holder1 setCurrentSharePrice:11];
    [holder1 setPurchaseSharePrice:9];
    [holder1 setNumberOfShares:200];
    StockHolding *holder2 = [[StockHolding alloc] init];
    [holder2 setCurrentSharePrice:50];
    [holder2 setPurchaseSharePrice:30];
    [holder2 setNumberOfShares:200];
    StockHolding *holder3 = [[StockHolding alloc] init];
    [holder3 setCurrentSharePrice:100];
    [holder3 setPurchaseSharePrice:40];
    [holder3 setNumberOfShares:1000];
    //Have to build an array and print out values of the stocks one by one next
    NSMutableArray *stockHolders = [NSMutableArray array];
    //Add items to array
    [stockHolders addObject:holder1];
    [stockHolders addObject:holder2];
    [stockHolders addObject:holder3];
    for (int i = 0; i < [stockHolders count]; i++) {
        StockHolding *temp = [stockHolders objectAtIndex:i];
        NSLog(@"The cost is %.2f and the value is %.2f", [temp costInDollars],[temp valueInDollars]);

return 0;