My Version in UK pounds ;-)


#1

Here is my version of the first class challenge, it was quite a challenge to start with, getting my head around the arrays… this is great book for anyone thinking about buying it.

If anyone has any ways of improving this or finds something i have missed please comment here.

@interface StockHolding : NSObject
{
    float purchaseSharePrice;
    float currentSharePrice;
    int numberOfShares;
}

// instance variables...
@property float purchaseSharePrice;
@property float currentSharePrice;
@property int numberOfShares;

// Create the instance methods...
-(float)costInPounds;
-(float)valueInPounds;

[code]
@implementation StockHolding

@synthesize purchaseSharePrice, currentSharePrice;
@synthesize numberOfShares;

-(float)costInPounds
{
return [self purchaseSharePrice] * [self numberOfShares];
}

-(float)valueInPounds
{
return [self currentSharePrice] * [self numberOfShares];
}

@end[/code]


StockHolding *stockHolder = [[StockHolding alloc] init];
        
        [stockHolder setPurchaseSharePrice:2.30];
        [stockHolder setCurrentSharePrice:4.50];
        [stockHolder setNumberOfShares:40];
        
        
        StockHolding *stockHolderTwo = [[StockHolding alloc] init];
        
        [stockHolderTwo setPurchaseSharePrice:12.19];
        [stockHolderTwo setCurrentSharePrice:10.56];
        [stockHolderTwo setNumberOfShares:90];
        
        StockHolding *stockHolderThree = [[StockHolding alloc] init];
        
        [stockHolderThree setPurchaseSharePrice:45.10];
        [stockHolderThree setCurrentSharePrice:49.51];
        [stockHolderThree setNumberOfShares:210];
        
        NSMutableArray *stockHolders = [[NSMutableArray alloc] initWithObjects:stockHolder, stockHolderTwo, stockHolderThree, nil];
        
        // Check how many objects in the array...
        NSLog(@"Array: %lu", [stockHolders count]);
        
        for(StockHolding *sh in stockHolders) {
            
            float cost = [sh costInPounds];
            float value = [sh valueInPounds];
            
            NSLog (@"Stock Holder: %lu You own: %i shares | Cost: $%.2f and they are worth: $%.2f\n", [stockHolders indexOfObject:sh] + 1, [sh numberOfShares], cost, value);
        }

OUTPUT

Array: 3
Stock Holder: 1 You own: 40 shares | Cost: £92.00 and they are worth: £180.00
Stock Holder: 2 You own: 90 shares | Cost: £1097.10 and they are worth: £950.40
Stock Holder: 3 You own: 210 shares | Cost: £9471.00 and they are worth: £10397.10

#2

Nailed it.