Completely stuck on Bronze challenge


#1

Hi everybody, i feel a little depressed because I’m completely stuck on this chapter’s challenges.

Bronze Challenge:
My approach was: creating 2 new mutable arrays, the first filled with Items with a value < 50$, the other one with the expensive items.

BNRItemStore.h

[code]
@class BNRItem;

@interface BNRItemStore : NSObject
{
NSMutableArray *allItems;
NSMutableArray *cheapItems;
NSMutableArray *expensiveItems;
}
// Notice that this is a class method and prefixed with a + instead of a -

  • (BNRItemStore *)sharedStore;
  • (NSArray *)cheapItems;
  • (NSArray *)expensiveItems;
  • (NSArray *)allItems;
  • (BNRItem *)createItem;

@end[/code]

BNRItemStore.m

...
- (NSArray *)allItems
{
    return allItems;
}
- (NSArray *)cheapItems
{
    return cheapItems;
}
- (NSArray *)expensiveItems
{
    return expensiveItems;
}

- (BNRItem *)createItem
{
    BNRItem *p = [BNRItem randomItem];
    [allItems addObject:p];
    
    if([p valueInDollars] < 50) {
        [cheapItems addObject:p];
        NSLog(@"Cheap Item added");
    } else {
        [expensiveItems addObject:p];
        NSLog(@"Expensive Item Added");
    }
    
    return p;
}

ItemsViewController.m

...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(section == 0) {
        return @"Less than 50$";
    } else {
        return @"More than 50$";
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0) {
        return [[[BNRItemStore sharedStore] cheapItems] count];
    } else {
        return [[[BNRItemStore sharedStore] expensiveItems] count];
    }
}
...

Now I can’t understand how to add these arrays to the right section in the Table View… I’ve tried something like:

[code]BNRItem *p;

switch ([indexPath section]) {
    case 0:

        p = [[[BNRItemStore sharedStore] cheapItems] objectAtIndex:[indexPath row]];
        [[cell textLabel] setText:[p description]];
        
        break;
    case 1:
        
        p = [[[BNRItemStore sharedStore] expensiveItems] objectAtIndex:[indexPath row]];
        [[cell textLabel] setText:[p description]];
        
        break;
    default:
        break;
}
    
return cell;[/code]

But it doesn’t work. Any hint?


#2

You could use the debugger to find out!

Set a breakpoint at your switch statement and then check the value of “p”.


#3

With the debugger I saw that cheapItems and expensiveItems where = null() and then I realized that I forgot to initialize the variables in BNRItemStore.m

This is the code:

- (id)init { self = [super init]; if(self) { allItems = [[NSMutableArray alloc] init]; cheapItems = [[NSMutableArray alloc] init]; expensiveItems = [[NSMutableArray alloc] init]; } return self; }