0

In one class there is a list with all friends and their IDs. Now when you click on the item in the UITableView the Chat appears ([self performSegueWithIdentifier: @"showChat" sender: self];). But in the ChatViewController Class I need to access the variable userID from FirstViewController. I tried everything I found on the internet, but it always gives an error or the variable is empty. In FirstViewController is a NSString userid, so how can I access this in ChatViewController.m? I tried to make the variable @public, I tried @property with readwrite and so on, but it doesn't work. For example this:

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

just gives an empty String..

Thanks for help!

Dion
  • 3,145
  • 20
  • 37

2 Answers2

4

You need to have prepareForSegue: method to pass the variable.

Implement the method as follows:

- (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;
    }
}

You can find the tutorial here on passing the value through segue.

Update

Similar question is already asked here

Community
  • 1
  • 1
Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55
3

You write this code in ChatViewController right . where u make a new instance of FirstViewController. And this is the problem new instance has userID always empty.

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

U need to have ur old instance of FirstViewController or when u go FirstViewController to ChatViewController u have to pass this value to userID = fvc.userID;

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

Bear in mind that u have set Property and synthesize the userID in ChatViewController.

gauravds
  • 2,931
  • 2
  • 28
  • 45