id到NSString在传递给另一个类时返回null

时间:2016-03-24 20:38:16

标签: ios objective-c segue

我有以下代码将该行发送到我的另一个类:

[self performSegueWithIdentifier:@"MeInfos" sender:[NSString stringWithFormat:@"%d",(int)indexPath.row]];

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    MeInfosViewController *viewController = [[MeInfosViewController alloc] init];
    viewController.paramethersToLoad = (NSString*)sender;
    NSLog(@"Will receive -> %@",sender);
}

在我的另一个类(MeInfoViewController)中,我有:

·H

@property (nonatomic, retain) NSString *paramethersToLoad;

的.m

@synthesize paramethersToLoad;

-(void)viewDidAppear:(BOOL)animated{
    NSLog(@"What comes? -> %@",paramethersToLoad);
}

此代码有一点问题,在控制台中我收到以下消息:

Will receive -> 4
What comes? -> (null)

为什么会发生这种情况以及解决问题的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

您在prepareForSegue中创建的视图控制器:不是segue实际加载的实例。实际显示的视图控制器由iOS运行时创建,并作为segue中的属性传递给您。

你想要的是:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    MeInfosViewController *viewController = (MeInfosViewController *)segue.destinationViewController;
    viewController.paramethersToLoad = (NSString *)sender;
}

答案 1 :(得分:2)

您的prepareForSegue应如下所示:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([[segue identifier] isEqualToString:@"MeInfos"]) {
         // Get reference to the destination view controller
          MeInfosViewController *viewController = [segue destinationViewController]; 

           viewController.paramethersToLoad = (NSString*)sender;
     }
}