views:

701

answers:

2

I keep getting 'warning: control reaches end of non-void function' with this code:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

 if (section ==0)

 {
  return [comparativeList count];
 }

 if (section==1) 
 {
  return [generalList count];
 }

 if (section==2)
 {

  return [contactList count];

How can I get rid of this warning?

Thanks.

+6  A: 

Add a return 0; at the end of your method. It's basically a failsafe, if none of the if conditions are met.

If you want to make sure one of the conditions is met, return -1; should cause the application to throw an exception and crash, which might help you track down errors.

You might also look at modifying this method and replacing the if statements with a switch-case tree. With a switch-case tree, you can very easily add new sections and rearrange their order in a UITableView. The code becomes trivially easy to read by using sensible naming conventions.

It's really easy; Fraser Speirs has a good explanation on how to set this up.

Alex Reynolds
+1, the OPs actual warning is likely "control reaches end of non- **void** function".
Carl Norum
Yep, basically any method or function that says it will return something should be returning something. As there's no guarantee that any of the `if` conditions will be met, it is possible nothing will get returned.
Alex Reynolds
Thanks very much it worked nicely, and your explanation was also very useful. I really appreciate your time :)
Dave
+1  A: 

One option:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section ==0) {
        return [comparativeList count];
    } else if (section==1) {
        return [generalList count];
    }
    // section == 2    
    return [contactList count];
}
Pablo Santa Cruz