Gold Challenge - My Solution


#1

Here is my solution for the Gold challenge for chapter 2. I appreciate any feedback on what I may have missed or programming style as I am still new to objective-c.

// BNRContainer.h

#import <Foundation/Foundation.h>
#import “BNRItem.h”

@interface BNRContainer : BNRItem
{
NSMutableArray *containerItems;
BNRItem *container;
}

-(id)initWithContainerName:(NSString *)name
containerValueInDollars:(int)value
containerSerialNumber:(NSString *)sNumber;

-(int)valueInDollars;

-(void)addItem:(id)itemToAdd;

@end

// BNRContainer.m

#import “BNRContainer.h”

@implementation BNRContainer

-(id)initWithContainerName:(NSString *)name
containerValueInDollars:(int)value
containerSerialNumber:(NSString *)sNumber
{
self = [super init];
if (self)
{
container = [[BNRItem alloc] initWithItemName:name
valueInDollars:value
serialNumber:sNumber];
containerItems = [NSMutableArray new];
}
return self;
}

-(id)init
{
return [self initWithContainerName:@“Container"
containerValueInDollars:0
containerSerialNumber:@” "];
}

-(int)valueInDollars
{
int retTotal = [container valueInDollars];
for (BNRItem *item in containerItems)
{
retTotal += [item valueInDollars];
}
return retTotal;
}

-(void)addItem:(id)itemToAdd
{
[containerItems addObject:itemToAdd];
}

-(NSString *)description
{
NSMutableString *descString = [[NSMutableString alloc] initWithFormat:@“Container %@ (%@): Worth $%d, recorded on %@”, [container ItemName], [container serialNumber], [container valueInDollars], [container dateCreated]];

for (int i = 0; i < [containerItems count]; i++)
{
[descString appendFormat:@"\n %@", [containerItems objectAtIndex:i]];
}
[descString appendFormat:@"\n Total Value: $%d", [self valueInDollars]];

return descString;
}

@end