问题
I have a tableview for which I am using
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
}
I have an NSArray *selectedDiscounts which I have assigned like this
selectedDiscounts = [self.tableView indexPathsForSelectedRows];
I have to pass the selected table rows data to another controller where I will be populating the tableView with selected rows.
The problem is selectedDiscounts either holds only selected indexPaths and not the data? because of which it shows me the number of objects that are selected but not the data for those selected cells.
I want to store the selected rows data into an NSArray variable. Is that possible? Thanks guys.
回答1:
You need to iterate through all of your index paths and get the data yourself.
NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSIndexPath *indexPath in selectedDiscounts) {
// Assuming self.data is an array of your data
[array addObject: self.data[indexPath.row]];
}
Now you have your NSArray that contains your data that can you pass to your next controller.
回答2:
Your selectedDiscounts
array is clearly being populated with the UITableView
method indexPathForSelectedRows
. To store the actual data for the selected rows you need to first establish an array allDiscounts
, with which you populate your first table view. Then, when you are displaying all of the objects from allDiscounts
and you want to select some and store the data do this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[selectedDiscounts addObject:[allDiscounts objectAtIndex:indexPath.row]];
}
回答3:
The way I would handle this, is to create a custom initializer method on the view controller you want to pass the data to. Something like this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *selectedDiscounts = yourDataSource[indexPath.row];
NewViewController *newVC = [[NewViewController alloc] initWithSelectedDiscounts:selectedDiscounts];
self.navigationController pushViewController:newVC animated:YES];
}
An alternate method would be create a property on the second view controller that is the array/dictionary you want to pass, and when they select the row, get the information for the row, and set it on the view controller before you push/present it.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *selectedDiscounts = yourDataSource[indexPath.row];
NewViewController *newVC = [[NewViewController alloc] initWith...// whatever you use for the initializer can go here...
newVC.discounts = selectedDiscounts;
self.navigationController pushViewController:newVC animated:YES];
}
来源:https://stackoverflow.com/questions/25532763/ios-i-am-trying-to-send-the-selected-rowsdata-to-another-controller