File: BNRStockHolding.h
[code]#import <Foundation/Foundation.h>
@interface BNRStockHolding : NSObject
@property (nonatomic) float purchaseSharePrice;
@property (nonatomic) float currentSharePrice;
@property (nonatomic) int numberOfShares;
- (float)costInDollars; // purchaseSharePrice * numberOfShares
- (float)valueInDollars; // currentSharePrice * numberOfShares
@end[/code]
File: BNRStockHolding.m
[code]#import “BNRStockHolding.h”
@implementation BNRStockHolding
-
(float)costInDollars
{
// using compiler generated accessors
// without accessing explicitly the ivars// purchaseSharePrice * numberOfShares
return [self purchaseSharePrice] * [self numberOfShares];
} -
(float)valueInDollars
{
// currentSharePrice * numberOfShares
return [self currentSharePrice] * [self numberOfShares];
}
@end[/code]
File: main.m
[code]#import <Foundation/Foundation.h>
#import “BNRStockHolding.h”
int main(int argc, const char * argv[])
{
@autoreleasepool {
// Chapter 18 Your First Class
// Challenge
BNRStockHolding *stock1 = [[BNRStockHolding alloc] init];
BNRStockHolding *stock2 = [[BNRStockHolding alloc] init];
BNRStockHolding *stock3 = [[BNRStockHolding alloc] init];
[stock1 setPurchaseSharePrice:2.30];
[stock1 setCurrentSharePrice:4.50];
[stock1 setNumberOfShares:40];
[stock2 setPurchaseSharePrice:12.19];
[stock2 setCurrentSharePrice:10.56];
[stock2 setNumberOfShares:90];
[stock3 setPurchaseSharePrice:45.10];
[stock3 setCurrentSharePrice:49.51];
[stock3 setNumberOfShares:210];
NSMutableArray *stockHolding = [[NSMutableArray alloc] initWithObjects:stock1, stock2, stock3, nil];
for (BNRStockHolding *s in stockHolding) {
NSLog(@"\n --Stock-- \nPurchase price: %.2f$ \nCurrent price: %.2f$ \nNumber of Shares: %i \nCost in dollars: %.2f$ \nValue in dollars: %.2f$", s.purchaseSharePrice, s.currentSharePrice, s.numberOfShares, s.costInDollars, s.valueInDollars);
}
}
return 0;
}[/code]
Output:
2014-08-21 08:53:10.434 Stocks[653:303]
–Stock–
Purchase price: 2.30$
Current price: 4.50$
Number of Shares: 40
Cost in dollars: 92.00$
Value in dollars: 180.00$
2014-08-21 08:53:10.435 Stocks[653:303]
–Stock–
Purchase price: 12.19$
Current price: 10.56$
Number of Shares: 90
Cost in dollars: 1097.10$
Value in dollars: 950.40$
2014-08-21 08:53:10.435 Stocks[653:303]
–Stock–
Purchase price: 45.10$
Current price: 49.51$
Number of Shares: 210
Cost in dollars: 9471.00$
Value in dollars: 10397.10$
Program ended with exit code: 0
Any suggestion will be appreciated.
Regards.,