Sahil Chaudhary
Sahil Chaudhary

Reputation: 503

difficulty using table view

I have created a small table view(no scroll) and want the user to select an option. To know which option was selected I defined an int type in header file of the view controller and exposed it as a property.I defined the method:

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
       //some code here/
       int optionSelected = indexPath.row;
}

Now I want to use this int optionSelected in other view controller but it doesn't work. Besides it gives an error in the function I defined above saying "Unused variable 'optionSelected'". Please tell me where can I possibly be going wrong. Thank you.

Upvotes: 0

Views: 56

Answers (3)

anuragbh
anuragbh

Reputation: 593

First, please note, optionSelected will save the row of the table that was selected, not the value selected. Second, you have created optionSelected as an instance variable of your current class, so it will not be directly accessible by any other class. To pass that value to the next view, add optionSelected as an instance variable in the header of the next view, just like you did in the current view. Then pass the value to the next view when you are configruing your next view, and then push it:

// 1) create next view 2) configure next view 3) push next view
UIViewController *nextViewController= [[UIViewController alloc] initWithNibName:@"nextViewController" bundle:nil];

nextViewController.optionSelected = optionSelected;

[self.navigationController pushViewController:_tabBarController animated:YES];

Upvotes: 0

jrturton
jrturton

Reputation: 119242

You're redeclaring optionSelected as a local variable in the code above. This means you aren't assigning it to your instance variable, so any attempt to use it later on won't work. Remove the int from the start of the line. This will remove the warning and, if everything else is OK, give you access to the selected row index elsewhere in your class.

Upvotes: 3

Ethan Holshouser
Ethan Holshouser

Reputation: 1401

In your code, int optionSelected defines a new integer with local scope - meaning it is only valid inside that method.

If you have exposed an int called optionSelected as a property, set it with self.optionSelected = indexPath.row or [self setOptionSelected:indexPath.row].

Upvotes: 0

Related Questions