2012-04-09 51 views
0

在一个课程中,列出了包含所有朋友及其ID的列表。现在,当您单击UITableView中的项目时,会出现“聊天”([self performSegueWithIdentifier: @"showChat" sender: self];)。但是在ChatViewController类中,我需要从FirstViewController访问变量userID。我尝试了我在互联网上找到的所有内容,但它总是给出错误或变量为空。 在FirstViewController是一个NSString userid,所以我怎么能在ChatViewController.m中访问这个?我试图使变量@public,我试图@property与readwrite等,但它不起作用。 例如对于这一点:将NSString授予其他课程

FirstViewController *fvc = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil]; 
userID = fvc.userID; 

只是给出了一个空字符串..

感谢您的帮助!

回答

4

您需要有prepareForSegue:方法来传递变量。

实现如下方法:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    // Make sure your segue name in storyboard is the same as this line 
    if ([[segue identifier] isEqualToString:@"showChat"]) 
    { 
     // Get reference to the destination view controller 
     ChatViewController *cvc = [segue destinationViewController]; 

     // Set the object to the view controller here, like... 
     cvc.userID = self.userID; 
    } 
} 

您可以传递值通过SEGUE找到tutorial here

更新

类似的问题已经被问here

4

你写在ChatViewController正确的验证码。你在哪里做一个FirstViewController的新实例。 这就是问题,新实例的userID始终为空。

FirstViewController *fvc = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil]; 
userID = fvc.userID; 

ü需要有乌尔FirstViewController的旧实例或当ü去FirstViewController到ChatViewController u必须将该值传递给用户id = fvc.userID;

ChatViewController *cvc = [ChatViewController new]; 
    cvc.userID = self.userID; 
[self.navigationController pushViewController:cvc animated:YES]; 

请记住,您已设置属性并在ChatViewController中合成userID。