Answer to challenge & pointer question


#1

Below is my answer to the StockHolding challenge. I’m still not completely clear on when to use pointers instead of just regular variables. The way I’ve used them so far is mostly to point to an object that’s been created. But I’ve seen it used numerous ways in the book and I can’t quite discern what the usage pattern is…

.h

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

@interface StockHolding : NSObject

{
float purchaseSharePrice;
float currentSharePrice;
int numberOfShares;
}

// Set the accessors
@property float purchaseSharePrice;
@property float currentSharePrice;
@property int numberOfShares;

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

@end[/code]

.m

[code]#import “StockHolding.h”

@implementation StockHolding

@synthesize purchaseSharePrice, currentSharePrice, numberOfShares;

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

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

@end[/code]

main()

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

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

@autoreleasepool {
    
    // Create instance 1 of StockHolding and assign values to instance variables
    StockHolding *mike = [[StockHolding alloc] init];
    
    [mike setPurchaseSharePrice:2.30];
    [mike setCurrentSharePrice:4.50];
    [mike setNumberOfShares:40];
    
    
    
    // Create instance 2 of StockHolding and assign values to instance variables
    StockHolding *joe = [[StockHolding alloc] init];
    
    [joe setPurchaseSharePrice:12.19];
    [joe setCurrentSharePrice:10.56];
    [joe setNumberOfShares:90];
    
    
    // Create instance 3 of StockHolding and assign values to instance variables
    StockHolding *reggie = [[StockHolding alloc] init];
    
    [reggie setPurchaseSharePrice:45.10];
    [reggie setCurrentSharePrice:49.51];
    [reggie setNumberOfShares:210];
    

    
    // Create array to hold objects
    NSArray *shareholders = [NSArray arrayWithObjects:mike, joe,
                             reggie, nil];
    
    // Loop through array and print out values
    for (StockHolding *person in shareholders) {
        
        int personPosition = [shareholders indexOfObject:person];
        
        NSLog(@"Stockholder %d own %i shares of stock. He bought it at $%.2f and it's now worth $%.2f\n", personPosition + 1, [person numberOfShares], [person costInDollars], 
              [person valueInDollars]);
    }
    
}
return 0;

}

[/code]

Compiles to:

Stockholder 1 own 40 shares of stock. He bought it at $92.00 and it’s now worth $180.00
Stockholder 2 own 90 shares of stock. He bought it at $1097.09 and it’s now worth $950.40
Stockholder 3 own 210 shares of stock. He bought it at $9471.00 and it’s now worth $10397.09