My challenge solution


#1

I replaced the allPossessions array with two arrays in PossessionStore.h:

@interface PossessionStore : NSObject {
    NSMutableArray *cheapPossessions;
    NSMutableArray *expensivePossessions;
}

+ (PossessionStore *)defaultStore;

- (NSArray *)cheapPossessions;
- (NSArray *)expensivePossessions;
- (Possession *)createPossession;

And the implementation in PossessionStore.m:

- (id)init {
    if (defaultStore) {
        return defaultStore;
    }
    self = [super init];
    if (self) {
        cheapPossessions = [[NSMutableArray alloc] init];
        expensivePossessions = [[NSMutableArray alloc] init];
   }
    return self;
}

- (NSArray *)cheapPossessions {
    return cheapPossessions;
}

- (NSArray *)expensivePossessions {
    return expensivePossessions;
}

- (Possession *)createPossession {
    Possession *p = [Possession randomPossession];
    if ([p valueInDollars] <= 50) {
        [cheapPossessions addObject:p];
    } else {
        [expensivePossessions addObject:p];
    }
    return p;
}

Then made use of these new arrays in ItemsViewController.m:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return @"Cheap Stuff";
    } else {
        return @"Expensive Stuff";
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return [[[PossessionStore defaultStore] cheapPossessions] count];
    } else {
        return [[[PossessionStore defaultStore] expensivePossessions] count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // Check for a reusable cell first, use it if it exists
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    
    // If there is no reusable cell of this type, create a new one
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                                    reuseIdentifier:@"UITableViewCell"] autorelease];
    }
    PossessionStore *ps = [PossessionStore defaultStore];
    Possession *p = nil;
    if ([indexPath section] == 0) {
        p = [[ps cheapPossessions] objectAtIndex:[indexPath row]];
    } else {
        p = [[ps expensivePossessions] objectAtIndex:[indexPath row]];
    }
    [[cell textLabel] setText:[NSString stringWithFormat:@"%@ %d", [p possessionName], [p valueInDollars]]];
        
    return cell;
}

It works perfectly.


#2

Thanks for posting. I was seriously misinterpreting the use of numberOfSectionsInTableView: until getting help from your response. Otherwise, I had the same paradigm in mind, especially of localizing the data manipulation to PossessionStore.