I don't understand Ch 22 Challenge


#1

Ch 22 Challenge:

[quote]
Re-open your project from the Chapter 21 challenge.

No one other than you (the creator of the BNRPortfolio class) needs to know that you are using an NSMutableArray to hold the BNRStockHolding instances.

Move the property declaration for the array into a class extension in BNRPortfolio.m and add methods to BNRPortfolio to allow the addition and removal of stock holdings.[/quote]

Moving the { NSMutableArray * _holdings;} to the implementation file is trivial…

#import "BNRStockPortfolio.h" @interface BNRStockPortfolio() { NSMutableArray * _holdings; } @end
But I don’t understand what to do with the methods to add/remove stock holdings. Are we supposed to rewrite the code so that we don’t call those methods in main.m, but in BNRStockPortfolio.m?


#2

They don’t want you to declare the add/remove methods as a class extension, they wouldn’t be accessible if you did. If you read carefully they say “…and add methods to BNRPortfolio (not BNRPortfolio.m) to allow the addition and removal of stock holdings.” so your BNRPortfolio.h file should look something like this:

#import <Foundation/Foundation.h>
// use @class so we can declare that this portfolio class will access the
// 'valueInDollars' instance variable from the BNRStockHolding class
@class BNRStockHolding;

@interface BNRPortfolio : NSObject

@property (nonatomic, copy) NSArray *holdings;

- (float)totalValue;
- (void)addHolding:(BNRStockHolding *)h;
- (void)removeHolding:(BNRStockHolding *)r;

@end

And your BNRPortfolio.m file:

@interface BNRPortfolio ()

{
    NSMutableArray *_holdings;
}

@end

@implementation BNRPortfolio

- (void)setHoldings:(NSArray *)s
{
    _holdings = [s mutableCopy];
}

- (NSArray *)holdings
{
    return [_holdings copy];
}

- (void)addHolding:(BNRStockHolding *)h
{
    // is the holdings array nil?
    if (!_holdings) {
        // create the array
        _holdings = [[NSMutableArray alloc] init];
    }
    // add the holding in to the holdings array
    [_holdings addObject:h];
}

// describe how removeHolding works
- (void)removeHolding:(BNRStockHolding *)r
{
    if (r) {
        [_holdings removeObject:r];
    }
}

@end

I hope that clarifies (and I hope I’m correct in my programming haha)