My BNRStockHolding Challenge solution

I used the values for purchasePrice, currentPrice, and numberOfShares that are given in the book. Here’s my code:

BNRStockHolding.h

#import <Foundation/Foundation.h>

@interface BNRStockHolding : NSObject

{
    //These are the instance variables
    float _purchaseSharePrice;
    float _currentSharePrice;
    int _numberOfShares;
}

// BNRPerson has methods to read and set its instance variables
- (float)purchaseSharePrice;
- (void)setPurchaseSharePrice:(float)p;
- (float)currentSharePrice;
- (void)setCurrentSharePrice:(float)c;
- (int)numberOfShares;
- (void)setNumberOfShares:(int)n;

// These are instance methods
- (float)costInDollars;   // purchaseSharePrice * numberOfShares
- (float)valueInDollars;  // currentSharePrice * numberOfShares

@end

BNRStockHolding.m

#import "BNRStockHolding.h"

@implementation BNRStockHolding

- (float)purchaseSharePrice
{
    return _purchaseSharePrice;
}

- (void)setPurchaseSharePrice:(float)p
{
    _purchaseSharePrice = p;
}

- (float)currentSharePrice
{
    return _currentSharePrice;
}

- (void)setCurrentSharePrice:(float)c
{
    _currentSharePrice = c;
}

- (int)numberOfShares
{
    return _numberOfShares;
}

- (void)setNumberOfShares:(int)n
{
    _numberOfShares = n;
}

- (float)costInDollars
{
    float p = [self purchaseSharePrice];
    return [self numberOfShares] * p;
}

- (float)valueInDollars
{
    float c = [self currentSharePrice];
    return [self numberOfShares] * c;
}

@end

main.m

#import <Foundation/Foundation.h>
#import "BNRStockHolding.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        BNRStockHolding *stock0 = [[BNRStockHolding alloc] init];
        BNRStockHolding *stock1 = [[BNRStockHolding alloc] init];
        BNRStockHolding *stock2 = [[BNRStockHolding alloc] init];
        
        [stock0 setPurchaseSharePrice:2.30];
        [stock0 setCurrentSharePrice:4.50];
        [stock0 setNumberOfShares:40];
        
        [stock1 setPurchaseSharePrice:12.19];
        [stock1 setCurrentSharePrice:10.56];
        [stock1 setNumberOfShares:90];
        
        [stock2 setPurchaseSharePrice:45.10];
        [stock2 setCurrentSharePrice:49.51];
        [stock2 setNumberOfShares:210];
        
        NSMutableArray *listOfStocks = [NSMutableArray array];
        
        [listOfStocks addObject:stock0];
        [listOfStocks addObject:stock1];
        [listOfStocks addObject:stock2];
        
        int stockNumber = 1;
        
        for (BNRStockHolding *s in listOfStocks) {
            float finalValue = [s valueInDollars] - [s costInDollars];
            NSLog(@"Your stake in stock #%d is currently worth %f", stockNumber, finalValue);
            stockNumber++;
        }
        
    }
    return 0;
}

Output:
Your stake in stock #1 is currently worth 88.000000
Your stake in stock #2 is currently worth -146.699951
Your stake in stock #3 is currently worth 926.099609

it’s good~