Challenge Solution


Here’s my go at the challenge.


[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;



[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];


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;


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?


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.


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