Gold Challenge Answer


#1

Simple solution to the Gold Challenge, works as specified in the challenge. I’ve used properties instead of writing my own accessors (not covered yet in the book).
Created a subclass of BNRItem called BNRContainer. This subclass has a method for including BNRItems and BNRContainers. It’s also got a method to calculate its total value.
Besides that I’m using the useful classes from BNRItem.

[size=150]Main.m[/size]

[code]#import <Foundation/Foundation.h>
#import “BNRItem.h”
#import “BNRContainer.h”

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

@autoreleasepool {
    
    //Create a mutable array object, store its address in items variable
    NSMutableArray *items = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < 10; i++) {
        BNRItem *item = [BNRItem randomItem];
        [items addObject:item];
    }
    
    for (BNRItem *item in items){
        NSLog(@"%@", item);
    }
    
    //Create a container class
    BNRContainer *container = [[BNRContainer alloc] initWithItemName:@"ConteContainer" valueInDollars:200 serialNumber:@"Mongomaniac"];
    
    //Add the BNRItems to the container class instance:
    for (BNRItem *item in items)
    {
        [container addToSubitems:item];
    }
    
    //Might as well add a container to the container to see if it can contain it :)
    BNRContainer *oneMoreContainer = [[BNRContainer alloc] initWithItemName:@"One More Container" valueInDollars:40 serialNumber:@"ABCEasyAs123"];
    
    //Add the container to the container
    [container addToSubitems:oneMoreContainer];
    
    //Print out the container
    NSLog(@"%@", container);
    
    //Destroy the mutable array object
    items = nil;
    
}
return 0;

}[/code]

[size=150]BNRContainer.h[/size]

[code]#import “BNRItem.h”

@interface BNRContainer : BNRItem
@property (nonatomic) NSMutableArray *subitems;

  • (int)valueOfContainer;
  • (void)addToSubitems:(id)itemObject;
    @end[/code]

[size=150]BNRContainer.m[/size]

[code]#import “BNRContainer.h”

@implementation BNRContainer

  • (NSString *)description
    {
    return [NSString stringWithFormat:@“Name of container: %@\r Containervalue in dollars: %d\r Total value in dollars:%d\r List of items:%@\r”, self.itemName, self.valueInDollars, self.valueOfContainer, self.subitems];
    }

  • (int)valueOfContainer
    {
    int sum = 0;
    for (BNRItem *item in [self subitems])
    {
    sum += item.valueInDollars;
    }

    for (BNRContainer *citem in [self subitems])
    {
    sum += citem.valueInDollars;
    }
    return sum;
    }

-(void)addToSubitems:(id)itemObject
{
if (!self.subitems) {
self.subitems = [[NSMutableArray alloc] init];
}
[self.subitems addObject:itemObject];
}

@end[/code]