Just thought I’d share my code with you guys, think it’s a pretty standard solution.
[code]// BNRStockHolding.h
#import <Foundation/Foundation.h>
@interface BNRStockHolding : NSObject
{
float _purchaseSharePrice;
float _currentSharePrice;
int _numberOfShares;
}
// accessor methods
- (float)purchaseSharePrice;
- (float)currentSharePrice;
- (int)numberOfShares;
// setter methods
- (void)setCostInDollars:(float)c;
- (void)setValueInDollars:(float)v;
- (void)setNumberOfShares:(float)s;
// getter methods
- (float)costInDollars; // purchaseSharePrice * numberOfShares
- (float)valueInDollars; // currentsharePrice * numberOfShares
// custom description method
- (void) getDescription:(BNRStockHolding *)s;
@end[/code]
[code]// BNRStockHolding.m
#import “BNRStockHolding.h”
@implementation BNRStockHolding
-
(float)purchaseSharePrice {
return _purchaseSharePrice;
} -
(float)currentSharePrice {
return _currentSharePrice;
} -
(int)numberOfShares {
return _numberOfShares;
} -
(void)setCostInDollars:(float)c {
_purchaseSharePrice = c;
} -
(void)setValueInDollars:(float)v {
_currentSharePrice = v;
} -
(void)setNumberOfShares:(float)s {
_numberOfShares = s;
} -
(float)costInDollars {
float pSP = [self purchaseSharePrice];
float nOS = [self numberOfShares];
return pSP * nOS;
} -
(float)valueInDollars {
float cSP = [self currentSharePrice];
float nOS = [self numberOfShares];
return cSP * nOS;
} -
(void)getDescription:(BNRStockHolding *)s {
NSLog(@"\nCost in Dollars: %.2f\nValue in Dollars: %.2f\n", [self costInDollars], [self valueInDollars]);
}
@end[/code]
[code]// main.m
#import <Foundation/Foundation.h>
#import “BNRStockHolding.h”
int main(int argc, const char * argv[]) {
@autoreleasepool {
// create an array to hold values
NSMutableArray *stockArray = [[NSMutableArray alloc]init];
// create an instance of BNRStockHolding
BNRStockHolding *stockOne = [[BNRStockHolding alloc]init];
// give the ivars values using setter methods
[stockOne setCostInDollars:2.30];
[stockOne setValueInDollars:4.50];
[stockOne setNumberOfShares:40];
// add 1st object to array
[stockArray addObject];
BNRStockHolding *stockTwo = [[BNRStockHolding alloc]init];
[stockTwo setCostInDollars:12.19];
[stockTwo setValueInDollars:10.56];
[stockTwo setNumberOfShares:90];
// add 2nd object
[stockArray addObject];
BNRStockHolding *stockThree = [[BNRStockHolding alloc]init];
[stockThree setCostInDollars:45.10];
[stockThree setValueInDollars:49.51];
[stockThree setNumberOfShares:210];
// add 3rd object
[stockArray addObject:stockThree];
// iterate objects in array
for (BNRStockHolding *s in stockArray) {
[s getDescription:s];
}
}
return 0;
}[/code]
And the output is:
2015-02-09 10:47:38.508 Stocks[1001:367576]
Cost in Dollars: 92.00
Value in Dollars: 180.00
2015-02-09 10:47:38.510 Stocks[1001:367576]
Cost in Dollars: 1097.10
Value in Dollars: 950.40
2015-02-09 10:47:38.510 Stocks[1001:367576]
Cost in Dollars: 9471.00
Value in Dollars: 10397.10
Program ended with exit code: 0
Let me know what you think?