Here is my code for both challenges. Any suggestions welcome!
BNRPortfolio.h
#import <Foundation/Foundation.h>
@class BNRStockHolding;
@interface BNRPortfolio : NSObject
@property (nonatomic, copy) NSArray *holdings;
- (NSArray *) mostValuableHoldings;
- (NSArray *) holdingsSortedAlphabetically;
- (float)totalValue;
- (void)addStock:(BNRStockHolding *)s;
- (void)removeStock:(BNRStockHolding *)r;
@end
BNRPortfolio.m
@interface BNRPortfolio ()
{
NSMutableArray *_holdings;
NSMutableArray *_mostValuableHoldings;
NSMutableArray *_holdingsSortedAlphabetically;
}
@end
...
// Most valuable holdings challenge
- (NSArray *)mostValuableHoldings
{
_mostValuableHoldings = [self.holdings mutableCopy];
NSSortDescriptor *vid = [NSSortDescriptor sortDescriptorWithKey:@"valueInDollars"
ascending:NO];
NSSortDescriptor *nos = [NSSortDescriptor sortDescriptorWithKey:@"nameOfStock"
ascending:YES];
[_mostValuableHoldings sortUsingDescriptors:@[vid, nos]];
NSInteger holdingsCount = [_mostValuableHoldings count];
while (holdingsCount > 3) {
[_mostValuableHoldings removeLastObject];
holdingsCount--;
}
return [_mostValuableHoldings copy];
}
// Holdings sorted alphabetically challenge
- (NSArray *)holdingsSortedAlphabetically
{
_holdingsSortedAlphabetically = [self.holdings mutableCopy];
NSSortDescriptor *nos = [NSSortDescriptor sortDescriptorWithKey:@"nameOfStock"
ascending:YES];
[_holdingsSortedAlphabetically sortUsingDescriptors:@[nos]];
return [_holdingsSortedAlphabetically copy];
}
Implementations in main.m
...
// Most valuable 3 holdings
NSLog(@"\nMost valuable 3 holdings");
for (BNRStockHolding *stock in stockHoldings.mostValuableHoldings) {
NSLog(@"Holdings sorted in descending order of value: %@, with a value of %.2f", stock.nameOfStock, stock.valueInDollars);
}
// Holdings sorted alphabetically challenge
NSLog(@"\nHoldings sorted alphabetically");
for (BNRStockHolding *stock in stockHoldings.holdingsSortedAlphabetically) {
NSLog(@"%@ stocks cost $%.2f, now worth $%.2f. Value changed by $%.2f.", stock.nameOfStock, stock.costInDollars, stock.valueInDollars, stock.totalLossGain);
}
...