Challenge solution


#1

Hello everybody!
I’m new at programming and objective-c.
Here is my solution to the chapter’s challenge, I’ll be appreciated with your feedback about it.
Thanks :wink:

StockHolding.h

[code]//
// StockHolding.h
// Stocks
//
//

#import <Foundation/Foundation.h>

@interface StockHolding : NSObject
@property float purchasePrice;
@property float currentPrice;
@property int numberOfShares;

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

@end
[/code]

StockHolding.m

[code]//
// StockHolding.m
// Stocks
//
//

#import “StockHolding.h”

@implementation StockHolding
@synthesize purchasePrice = _purchasePrice;
@synthesize currentPrice = _currentPrice;
@synthesize numberOfShares = _numberOfShares;

-(float)costInDollars{
return self.purchasePrice * self.numberOfShares;
}
-(float)valueInDollars{
return [self currentPrice] * [self numberOfShares];
}
@end
[/code]

main.m

[code]//
// main.m
// Stocks
//
//

#import <Foundation/Foundation.h>
#import “StockHolding.h”

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

@autoreleasepool {
    //  init 3 StockHolding elements
    StockHolding *firstStock = [[StockHolding alloc] init];
    StockHolding *secondStock = [[StockHolding alloc] init];
    StockHolding *thirdStock = [[StockHolding alloc] init];
    
    // set their params
    [firstStock setCurrentPrice:4.5];
    [firstStock setPurchasePrice:2.3];
    [firstStock setNumberOfShares:40];
    
    [secondStock setCurrentPrice:10.56];
    [secondStock setPurchasePrice:12.19];
    [secondStock setNumberOfShares:90];
    
    [thirdStock setCurrentPrice:49.51];
    [thirdStock setPurchasePrice:45.10];
    [thirdStock setNumberOfShares:210];
    
    // Put them in array
    NSMutableArray *stocks = [NSMutableArray arrayWithObjects:firstStock, secondStock, thirdStock, nil];
    
    //  Output 
    for (StockHolding *s in stocks) {
        NSLog(@"Cost in dollars is %.2f, value in dollars is %.2f, number of shares is %d", [s costInDollars], [s valueInDollars], [s numberOfShares]);
    }
}
return 0;

}[/code]


#2

Seems good, but I don’t think you need to declare names of variables (If that’s what they are) after you @synthesize the normal properties. Why did you add the “=_name”?

My StockHolding.m looks like this:

[code]@implementation StockHolding

//@synthesize implements setter and getter methods for the properties

@synthesize numberOfShares, purchaseSharePrice, currentSharePrice;

  • (float)costInDollars
    {
    return purchaseSharePrice * numberOfShares;
    }

  • (float)valueInDollars
    {
    return currentSharePrice * numberOfShares;
    }

[/code]


#3

Thank you for response! :slight_smile:
I did that because I heard somewhere that it is something like good manners in writing code. It’s always we can see where I’m calling get/set function and where I’m working directly with variable. For example, if I would like to change implementation of set/get function for this variable - I can use _name directly in them.