My Gold Solution - Feedback appreciated!


#1

BNRContainer.h

#import "BNRItem.h"

@interface BNRContainer : BNRItem
{
    NSMutableArray *_subItems;
}

-(NSMutableArray *)subItems;

-(void)addItem:(BNRItem *)item;

@end

BNRContainer.m

#import "BNRContainer.h"

@implementation BNRContainer

-(NSString *)description
{
    if ([self.subItems count]) {
        return [[super description] stringByAppendingString:[self.subItems description]];
    } else {
        return [super description];
    }
}

-(NSMutableArray *)subItems
{
    if (!_subItems) {
        _subItems = [NSMutableArray new];
    }
    return _subItems;
}

-(int)value
{
    int total = 0;
    if ([self.subItems count]) {
        for (BNRItem *item in self.subItems) {
            total += item.value;
        }
    }
    return _value + total;
}

-(void)addItem:(BNRItem *)item
{
    [self.subItems addObject:item];
}

@end

main.m

#import <Foundation/Foundation.h>
#import "BNRContainer.h"

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        BNRContainer *myContainer = [[BNRContainer alloc]initWithName:@"My Container"
                                                         serialNumber:@"A1B2C3"
                                                       valueInDollars:100000];
        NSLog(@"Value of myContainer: %d",myContainer.value);
        
        BNRItem *myItem = [[BNRItem alloc]initWithName:@"My Item"
                                          serialNumber:@"A2B3C4"
                                        valueInDollars:22222];
        
        [myContainer addItem:myItem];
        
        NSLog(@"Value after adding an item: %d",myContainer.value);
        
        BNRItem *randItem = [BNRItem randomItem];
        NSLog(@"Random Item: %@",randItem);
        [myContainer addItem];
        
        BNRContainer *randomContainer = [BNRContainer randomItem];
        NSLog(@"Random Container: %@",randomContainer);
        [randomContainer addItem:myItem];

        [myContainer addItem:randomContainer];        
        NSLog(@"%@",myContainer);
    }
    return 0;
}