Challenge: Sections (Compile problem)


#1

Hi,

I’d be very grateful for some help here - I’m attempting the challenge and wrote the following in ItemsViewController.m

-(UITableViewCell *)tableView:(UITableView *) tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell =
	[tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
	
	if (!cell)
		{
		cell = [[[UITableViewCell alloc]
				 initWithStyle:UITableViewCellStyleDefault
				 reuseIdentifier:@"UITableViewCell"] autorelease];
		}
	
	switch ([indexPath section])
	{
        case 0:
			; /* <---- Need this semi colon to compile */
			Possession *p = [possessions objectAtIndex:[indexPath row]];
			[[cell textLabel] setText:[p description]];
            break;
        case 1:
			; /*  <---- Need this semi colon to compile */
			Possession *pOverFifty = [possessionsOverFifty objectAtIndex:[indexPath row]];
			[[cell textLabel] setText:[pOverFifty description]];
            break;
    }
	
	return cell;
}

If I leave the semi colons in place then it compiles and actually works - hurrah !..

but if remove them or comment them out then it wont compile and I get

…/Homepwner copy/Classes/…/ItemsViewController.m:74: error: expected expression before ‘Possession’

I’ve checked syntax and can’t see why they’re needed - can anyone advise ?

Thanks


#2

This is a nuance of C (perhaps just C99, but I can’t remember). You will need curly braces for each case statement.

switch ([indexPath section])
{
        case 0:
        {
              Possession *p = [possessions objectAtIndex:[indexPath row]];
              [[cell textLabel] setText:[p description]];
        } break;
        case 1:
        {
              Possession *pOverFifty = [possessionsOverFifty objectAtIndex:[indexPath row]];
              [[cell textLabel] setText:[pOverFifty description]];
        } break;
}

There are some weird rules about how statements are executed and variable declaration within a switch statement. Those rules also change between versions of C, AFAIK. Safest way is to use curly braces for each case.


#3

Thanks Joe - works a treat.


#4

Senior moment here…I thought I understood where to declare possessionsOverFifty but I didn’t. I get a possessionsOverFifty undeclared. Where do I declare it? Thanks for helping a noob.


#5

duhhhhh, slap upside the head.