Another more DRY solution


I didn’t like the way setting each value for every stock:

[stock1 setPurchaseSharePrice:10];
[stock1 setCurrentSharePrice:100];
[stock1 setNumberOfShares:1000];

[stock2 setPurchaseSharePrice:10];
[stock2 setCurrentSharePrice:100];
[stock2 setNumberOfShares:1000];


So I decided to declare an additional method named stock, which does all the work for me and I don’t have to repeat myself.


#import <Foundation/Foundation.h>

@interface StockHolding : NSObject

@property float purchaseSharePrice, currentSharePrice;
@property int numberOfShares;

- (float) costInDollars;
- (float) valueInDollars;
- (StockHolding *)stock:(float)purchasedPrice :(float)currentPrice :(int)numberShares;



#import "StockHolding.h"

@implementation StockHolding

@synthesize purchaseSharePrice, currentSharePrice, numberOfShares;

- (float)costInDollars
    return purchaseSharePrice * numberOfShares;

- (float)valueInDollars
    return currentSharePrice * numberOfShares;

- (StockHolding *)stock:(float)purchasedPrice :(float)currentPrice :(int)numberShares
    [self setPurchaseSharePrice:purchasedPrice];
    [self setCurrentSharePrice:currentPrice];
    [self setNumberOfShares:numberShares];
    return self;



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

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

    @autoreleasepool {
        StockHolding *google = [[StockHolding alloc] init];
        StockHolding *yahoo = [[StockHolding alloc] init];
        StockHolding *ebay = [[StockHolding alloc] init];
        [google stock:398.21 :768.59 :10];
        [yahoo stock:7.78 :28.67 :500];
        [ebay stock:36.11 :57.46 :75];
        NSArray *allStocks = [NSArray arrayWithObjects:google, yahoo, ebay, nil];
        for (StockHolding *s in allStocks) {
            NSLog(@"price: %.2f, current: %.2f, number: %d, costs: %.2f, value: %.2f", [s purchaseSharePrice], [s currentSharePrice], [s numberOfShares], [s costInDollars], [s valueInDollars]);
    return 0;


This is exactly like mine. The only thing I can’t do is to make it print object names in the beginning of every line. It prints object address but not object name. Any ideas?

for (StockHolding *d in array)
            NSLog(@" %@ purchase price: %.2f stock current price: %.2f number of shares: %d bought for $%.2f sell now for $%.2f ", d, [d purchaseSharePrice], [d currentSharePrice], [d numberOfShares],[d costInDollars] ,[d valueInDollars]);