(In the previous post I asked help because in the first challenge I got an error. I edited the previous message because I realized that I made a super-stupid mistake: in BNRStockHolding.h, I called the variable “valueIndollars” and in the code here I used valueInDollars).
Here is my solution. Below the code of BNRPortfolio.h and .m
BNRPortfolio.h
#import <Foundation/Foundation.h>
@class BNRStockHolding;
@interface BNRPortfolio : NSObject
@property (nonatomic, copy) NSArray *holdings;
//@property (nonatomic, copy) NSArray *orderedPortfolio;
//@property (nonatomic, copy) NSArray *displayTop3;
- (NSArray *)holdingOrdered;
- (NSArray *)displayTop3;
- (float) currentValueOfPortfolio;
- (void) addStock:(BNRStockHolding *)stock;
- (void) removeStock:(BNRStockHolding *)stock;
@end
BNRPortfolio.m
#import "BNRStockHolding.h"
#import "BNRForeignStockHolding.h"
#import "BNRPortfolio.h"
@interface BNRPortfolio ()
{
NSMutableArray *_holdings;
NSMutableArray *_holdingOrdered;//challenge2
NSMutableArray *_displayTop3;//challenge1
}
@end
@implementation BNRPortfolio
-(void) setHoldings:(NSArray *)h
{
_holdings = [h mutableCopy];
}
- (NSArray *)holdings
{
return [_holdings copy];
}
- (NSArray *)holdingOrdered
{
_holdingOrdered = [self.holdings mutableCopy];
NSSortDescriptor *smb = [NSSortDescriptor sortDescriptorWithKey:@"symbol" ascending:YES];
[_holdingOrdered sortUsingDescriptors:@[smb]];
return [_holdingOrdered copy];
}
- (NSArray *) displayTop3
{
//We order the array _holdings:
NSSortDescriptor *vid = [NSSortDescriptor sortDescriptorWithKey:@"valueIndollars"
ascending:NO];//vid means value in dollars
[_holdings sortUsingDescriptors: @[vid]];
//we have to return the elements 0,1,2 of _holdings. So we copy these items in a new array called top3. First we create it (if _holdings contains more than 3 elements!):
if (_holdings.count>3){
NSMutableArray *top3 = [[NSMutableArray alloc] init];
for (int i=0; i<3; i++) {
[top3 insertObject:[_holdings objectAtIndex:i] atIndex:i];
}
return [top3 copy];
} else{
return _holdings;
}
}
- (float) currentValueOfPortfolio
{
float total = 0;
for (BNRStockHolding *stock in self.holdings)
{
total += stock.valueIndollars;
}
return total;
}
- (void) addStock:(BNRStockHolding *)s
{
if (!_holdings)//if holdings = nil the you must create it. Then you add the object.
{
_holdings = [[NSMutableArray alloc] init];
}
[_holdings addObject: s];
}
- (void) removeStock:(BNRStockHolding *)s
{
if (!_holdings)
{
return NSLog(@"ERROR.");
} else {
[_holdings removeObject: s];
}
}
@end