Challenge Solution


#1

Here’s my go at the challenge.

Stockholding.h

[code]#import <Foundation/Foundation.h>

@interface StockHolding : NSObject
{
float purchaseSharePrice;
float currentSharePrice;
int numberOfShares;
}
@property float purchaseSharePrice;
@property float currentSharePrice;
@property int numberOfShares;

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

@end
[/code]

stockholding.m

[code]#import “StockHolding.h”

@implementation StockHolding

@synthesize currentSharePrice;
@synthesize purchaseSharePrice;
@synthesize numberOfShares;

  • (float) costInDollars
    {
    return [self purchaseSharePrice] * [self numberOfShares];
    }
  • (float) valueInDollars
    {
    return [self currentSharePrice] * [self numberOfShares];
    }

@end[/code]

and main.m

[code]#import <Foundation/Foundation.h>
#import "StockHolding.h"
int main(int argc, const char * argv[])
{

@autoreleasepool {
    StockHolding *Apple = [[StockHolding alloc] init];
    StockHolding *Microsoft = [[StockHolding alloc] init];
    StockHolding *Amazon = [[StockHolding alloc] init];
    
    [Apple setPurchaseSharePrice:2.3];
    [Apple setCurrentSharePrice:4.5];
    [Apple setNumberOfShares:40];
    [Microsoft setNumberOfShares:90];
    [Microsoft setCurrentSharePrice:10.56];
    [Microsoft setPurchaseSharePrice:12.19];
    [Amazon setPurchaseSharePrice:45.1];
    [Amazon setNumberOfShares:210];
    [Amazon setCurrentSharePrice: 49.51];
    
    NSMutableArray *portfolio = [NSMutableArray array];
    [portfolio addObject:Apple];
    [portfolio addObject:Microsoft];
    [portfolio addObject:Amazon];
    
    for (StockHolding *d in portfolio) {
        NSLog(@"This stock's purchase value was %.2f, its current value is %.2f, you have %d stocks, you purchased it for %.2f a stock, and it is currently %.2f a stock\n\n\n", [d costInDollars], [d valueInDollars], [d numberOfShares], [d purchaseSharePrice], [d currentSharePrice] );
    }
    
}
return 0;

}
[/code]

I also printed out the stocks purchase price, current share price, and value in dollars.

Does anyone know how to print out the stock’s name (e.g. apple, microsoft, etc) in fast iteration besides making a variable that holds the object’s name?
Or just in general how to access an object’s name without creating a variable that holds it?
thanks


#2

Objective-C objects do not have intrinsic names, with one exception; only class object have names.

By the way, using variable names starting with capital letters is not a good practice because they then look like class names.


#3

Ok thanks for the tip ill look out for that in the future.