我有一个带有三个过渡的segue(参见下面的代码)。第一个来自一个按钮。这非常有效。第二种是通过在表格视图中点击单元格。那个也很完美。第三个是tableview单元格中的附件按钮。这个打开了正确的视图控制器,但没有像我编码那样传递对患者的引用。我已经通过新视图控制器的viewDidLoad中的NSLog语句验证了这一点,并将患者显示为null。
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:@"addPatient"]) {
// to add a new patient (selection segue)
UINavigationController *navigationController = segue.destinationViewController;
RXAddPatientViewController *addPatientViewController = (RXAddPatientViewController*)navigationController.topViewController;
Patient *addPatient = [NSEntityDescription insertNewObjectForEntityForName:@"Patient" inManagedObjectContext:[self managedObjectContext]];
addPatientViewController.addPatient = addPatient;
}
if ([[segue identifier] isEqualToString:@"toPrescriptions"]) {
// to view prescriptions for the selected patient (selection segue)
RXPrescriptionsViewController *prescriptionViewController = [segue destinationViewController];
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
Patient *selectedPatient = (Patient*) [self.fetchedResultsController objectAtIndexPath:indexPath];
prescriptionViewController.selectedPatient = selectedPatient;
NSLog(@"Selected Patient is %@", selectedPatient.patientFirstName);
}
if ([[segue identifier] isEqualToString:@"editPatient"]) {
// to edit the selected patient (accessory action)
UINavigationController *navigationController = segue.destinationViewController;
RXEditPatientViewController *editPatientViewController = (RXEditPatientViewController*)navigationController.topViewController;
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
Patient *editPatient = (Patient*) [self.fetchedResultsController objectAtIndexPath:indexPath];
// passing a reference to the editPatientViewController
editPatientViewController.editPatient = editPatient;
NSLog(@"Selected patient is %@", editPatient.patientFirstName);
}
}
答案 0 :(得分:2)
当您单击附件按钮时,indexPathForSelectedRow将为null,因为您没有选择该行。但是,prepareForSegue:sender:中的sender参数将是包含附件按钮的单元格。因此,您应该使用以下方法来获取indexPath(请注意我已将参数的类型从id更改为UITableViewCell):
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UITableViewCell *)sender {
if ([[segue identifier] isEqualToString:@"editPatient"]) {
// to edit the selected patient (accessory action)
UINavigationController *navigationController = segue.destinationViewController;
RXEditPatientViewController *editPatientViewController = (RXEditPatientViewController*)navigationController.topViewController;
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
Patient *editPatient = (Patient*) [self.fetchedResultsController objectAtIndexPath:indexPath];
// passing a reference to the editPatientViewController
editPatientViewController.editPatient = editPatient;
NSLog(@"Selected patient is %@", editPatient.patientFirstName);
}