@property NSMutableArray (...)


#1

Had problems with this one, as I wanted my clients to have a portfolio of many stocks.

I finally found an easy solution which might be dirty in some way…

I have the following

//  BNRStockHolding.h
//  BMITime

#import <Foundation/Foundation.h>

@interface BNRStockHolding : NSObject

@property double purchasePrice;
@property double currentPrice;
@property unsigned int numberOfShares;
@property NSString *stockName;

- (float) costInDollars;
- (float) valueInDollars;

@end

I have the following lines added in BNREmployee.h

[code]#import “BNRPerson.h”
#import “BNRAsset.h”
#import “BNRStockHolding.h”

@interface BNREmployee : BNRPerson

(…)

@property (nonatomic) NSMutableArray *stocks;

  • (NSMutableArray *)stocks;

(…)

@end
[/code]

  • (NSMutableArray *)stocks is the getter in BNREmployee.m that creates the array on the fly. The NSMutableArray *stocks can only exist if you create the getter…

[code]//Class extension
@interface BNREmployee()
{
(…)
NSMutableArray *_stocks;
}
@end

@implementation BNREmployee

(…)

  • (NSMutableArray *)stocks {
    if (!_stocks) _stocks = [[NSMutableArray alloc] init];
    return _stocks; }

@end
[/code]

I created a random set of stocks for the employee…

[code] void fillStocksRandomly(BNREmployee *employee)
{
BNRStockHolding *stockHolding;

int nStocks = 1 + (rand() % 5);
for (int i = 0; i < nStocks; i++)
{
	stockHolding = [[BNRStockHolding alloc]init];
	stockHolding.numberOfShares = 1 + (rand() % 1000);
	stockHolding.purchasePrice = 1 + (rand() % 100) +(rand() % 100)/100.0;
	stockHolding.currentPrice = stockHolding.purchasePrice * ((rand() % 1000)/500.0);
	[employee.stocks addObject:stockHolding];
}

}[/code]

From now on, all employees have different bunches of stocks, which can be accessed through the following:

[code] //eCount = number of employees

	BNREmployee *whatStocks;
	BNRStockHolding *theStocks;
	for (int i = 0; i < eCount; i++) {
		whatStocks = employees[i];
		unsigned long sCount = whatStocks.stocks.count;
		NSLog(@"Employee #%d has %lu stocks", i, sCount);
		for(int j = 0; j < sCount; j++) {
			theStocks = whatStocks.stocks[j];
			NSLog(@"    Stock #%d was purchased at $%.2f", j, theStocks.costInDollars);
			NSLog(@"    Stock #%d is now worth $%.2f", j, theStocks.valueInDollars);
		}
	}

[/code]