As nice as it gets


#1

Hello all,

here is my solution for this challenge.

[code]// Stockholding.h

#import <Foundation/Foundation.h>

@interface Stockholding : NSObject
{
// Question for the pros: Do I still need to declare variables here
// although they are declared as @property (see below)?
// This code is working without a (second) declaration
}
@property float purchaseSharePrice, currentSharePrice;
@property int numberOfShares;

  • (float)costInDollars;
  • (float)valueInDollars;
  • (NSString *)description;
    @end
    [/code]

[code]// Stockholding.m

#import “Stockholding.h”

@implementation Stockholding

@synthesize purchaseSharePrice, currentSharePrice, numberOfShares;

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

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

  • (NSString *)description
    {
    // Let’s output everything important about this Stockholding
    // in case somebody wants a description via NSLog (@"%@", …)
    return [NSString stringWithFormat:@“Number of shares: %d\nCost per share: %.2f\nTotal cost: %.2f\n----------------\nCurrent price per share: %.2f\nTotal value: %.2f”, [self numberOfShares], [self purchaseSharePrice], [self costInDollars], [self currentSharePrice], [self valueInDollars]];
    }
    @end
    [/code]

[code]// main.m

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

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

@autoreleasepool {

	// Create and define first stock
	Stockholding *stockOne = [[Stockholding alloc] init];
	[stockOne setPurchaseSharePrice:2.30];
	[stockOne setCurrentSharePrice:4.50];
	[stockOne setNumberOfShares:40];
	
	// Create and define second stock
	Stockholding *stockTwo = [[Stockholding alloc] init];
	[stockTwo setPurchaseSharePrice:12.19];
	[stockTwo setCurrentSharePrice:10.56];
	[stockTwo setNumberOfShares:90];
	
	// Create and define third stock
	Stockholding *stockThree = [[Stockholding alloc] init];
	[stockThree setPurchaseSharePrice:45.10];
	[stockThree setCurrentSharePrice:49.51];
	[stockThree setNumberOfShares:210];

	// Create array and fill with stocks from above
	NSMutableArray *stocks = [NSMutableArray arrayWithObjects:stockOne, stockTwo, stockThree, nil];

	// The NSLog in this for loop outputs the description of each Object in the array
	// Stockholding overwrites the description to simplify the loop and to have a nicer output
	for ( Stockholding *stock in stocks ) {
		NSLog(@"%@", stock);
	}
}
return 0;

}[/code]

The notable thing about this solution is the very simple enumeration at the end that consists of a very short NSLog. The real work is done in the class where the description method has been overwritten.

Happy coding

iFlash