This is called PERFECT GRILLIN!


#1

Iam a proud owner of this BOOK and I just want to say that I haven’t seen anyone delivering such a complicated Object Oriented Approach any better than in this chapter.

//main.m////////////////////////////////
        
        Portfolio *myPortfolioOfStocks=[[Portfolio alloc] init];
        
        for(int i=0;i<5;i++)
        {
            StockHolding *s=[[StockHolding alloc] init];
            s.purchaseSharePrice=2.3*i;
            s.currentSharePrice=3.8*i;
            s.numberOfShares=0.94*i;
            
            [myPortfolioOfStocks addStocks:s];
            
        }
        
        NSLog(@"My Portfolio contains: %lu Stock(s), their value is: %0.2f and their total cost is: %0.2f",
              [myPortfolioOfStocks totalStockInArray],
              [myPortfolioOfStocks totalStocksValue],
              [myPortfolioOfStocks totalStocksCost]);

[code]//Portfolio.h///////////////////
#import <Foundation/Foundation.h>
#import “StockHolding.h”

@interface Portfolio : NSObject
{
NSMutableArray *stocks;
float totalStocksValueCount;
float totalStocksCostCount;
}

-(void)addStocks:(StockHolding*)s;
-(float)totalStocksValue;
-(float)totalStocksCost;
-(long)totalStockInArray;

@end
[/code]

I think I should have these two “totalStocksValueCount” and “totalStocksCost” as local vars instead of global, so that they are only created when the method is called and destroyed from the memory rightaway !!

[code]//Portfolio.m///////////////////
#import “Portfolio.h”

@implementation Portfolio

-(void)addStocks:(StockHolding*)s{
if(!stocks){
stocks=[[NSMutableArray alloc]init];
}
[stocks addObject:s];
}
-(float)totalStocksValue{
totalStocksValueCount=0;
for(StockHolding* s in stocks){
totalStocksValueCount+=[s valueInDollars];
}
return totalStocksValueCount;
}
-(float)totalStocksCost{
totalStocksCostCount=0;
for(StockHolding* s in stocks){
totalStocksCostCount+=[s costInDollars];
}
return totalStocksCostCount;
}
-(long)totalStockInArray{
return [stocks count];
}
@end
[/code]

Because we have two methods in StockHolding, one which calculates the value and other cost from previous chapters. I have used two diff methods inside Portfolio.m to retrieve sum of each.
There it is:
2011-11-16 22:17:00.786 Learning1[1171:707] My Portfolio contains: 5 Stock(s), their value is: 76.00 and their total cost is: 46.00


#2

Thanks a bunch! I’ve been teaching this stuff a while now, and this book was a very exciting effort to get my approach on paper. I’m glad it is working for you.


#3

Looking at your header I saw those two floats declared.

float totalStocksValueCount; float totalStocksCostCount;

You shouldn’t need those at all since they are fully encapsulated by the class. Case in point you don’t synthesize or make any accessors for them in Portfolio.m.