您需要覆盖prepareForSegue:sender:
方法。快速修复将是
- (void)showList:(Subject *)subject animated:(BOOL)animated
{
[self performSegueWithIdentifier:@"showDetail" sender:subject];
}
...
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"showDetail"]) {
ListsViewController *controller = ([segue.destinationViewController isKindOfClass:[ListsViewController class]]) ? segue.destinationViewController : nil;
controller.subject = ([sender isKindOfClass:[Subject class]]) ? subject : nil;
}
}
您的代码不起作用的原因是,在您的showList:animated:
方法中,您创建了一个ListsViewController
实例并为其分配了一个subject
,但该视图控制器从未出现过。而是performSegueWithIdentifier:sender
创建你的ListsViewController
类的另一个实例,它对你的subject
. 这就是为什么您需要等待 UIStoryboardSegue 从情节提要中实例化目标视图控制器,然后按照您想要的方式对其进行配置,您可以在prepareForSegue:sender:
方法中执行此操作。
subject
此外,在方法中用作发件人可能不是最好的主意performSegueWithIdentifier:sender
,因为它不是发件人:)。我要做的是在您的视图控制器类中创建一个属性主题并使用它prepareForSegue:sender:
@interface MyViewController ()
@property (strong, nonatomic) Subject *subject;
@end
@implementation MyViewController
- (void)showList:(Subject *)subject animated:(BOOL)animated
{
self.subject = subject;
[self performSegueWithIdentifier:@"showDetail" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"showDetail"]) {
ListsViewController *controller = ([segue.destinationViewController isKindOfClass:[ListsViewController class]]) ? segue.destinationViewController : nil;
controller.subject = self.subject;
}
}
...
@end