Here is my solution, so far. Comments appreciated


#1

I finally found a solution, but I am not sure. Please have a look, all comments are very welcome.

Portfolio.h : only used for a sum method to total all current values of stock items

#import <Foundation/Foundation.h>
//@class StockHolding;

@interface Portfolio : NSObject 

-(float)totalValue:(NSMutableArray *)array;

@end

Portfolio.m

#import "Portfolio.h"
#import "StockHolding.h"

@implementation Portfolio

- (float)totalValue:(NSMutableArray *)array {
    float sum = 0;
    for (StockHolding *f in array) {
        sum += [f valueInDollars];
    }
    NSLog(@"Total value of portfolio is %.2f", sum);
    return sum;
}
@end

Stockholding.h

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

@interface StockHolding : NSObject
{
float purchasePrice;
float currentPrice;
int numberOfShares;
NSString *name;
}

@property float purchasePrice;
@property float currentPrice;
@property int numberOfShares;
@property NSString *name;

//accessor methods

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

@end
[/code]

stockholding.m

#import "StockHolding.h"

@implementation StockHolding

@synthesize purchasePrice, currentPrice, numberOfShares, name;

-(float) costInDollars {
    return purchasePrice * numberOfShares;
}

-(float) valueInDollars {
    return currentPrice * numberOfShares;
}
@end

main.m

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

int main(int argc, const char * argv[])
{
    @autoreleasepool {       
        //create array which holds all stocks/funds
        NSMutableArray *stockList = [[NSMutableArray alloc]init];

        //create 10 funds
        for (int i =0; i<10; i++) {
            StockHolding *fund = [[StockHolding alloc]init];
            NSString *fundName = [NSString stringWithFormat:@"Fund %d", i];
            [fund setName];
            [fund setPurchasePrice:12+i];
            [fund setCurrentPrice:5*i];
            [fund setNumberOfShares:100*i];
       //and add new fund to array stockList
            [stockList addObject:fund];
            
        //This NSLog logs every new object, one by one.
            NSLog(@"Portfolio holds stock %@, with current value %.2f", [fund name], [fund valueInDollars])   
        }
        
        //create an Portfolio object to call totalValue: method and pass MutArray stockList into it
        Portfolio *total = [[Portfolio alloc]init];
         [total totalValue:stockList];
        
    }
    return 0;
}

Does this make sense?