Poles
Poles

Reputation: 3682

iOS - Pass Data from one viewController to another using tabBarController in xib

I have a requirement where I have to pass a string value from one viewController to another on button click. I also need to switch from current viewController to secondViewController using tabBarController. I tried:

FirstViewController.h

#import "SecondViewController.h"

@property(nonatomic, strong) SecondViewController *secondController;

FirstViewController.m

-(IBAction)go:(id)sender
{
   self.secondController.itemText=@"Demo Text";
   self.tabBarController.selectedIndex=1; //say secondViewController index is 1
}

SecondViewController.h

#import "FirstViewController.h"

@property(nonatomic, strong) NSString *itemText;

SecondViewController.m

  -(void) viewWillAppear (BOOL) animated
    {
       NSLog(@"Comes from FirstViewController: %@",self.itemText);
    }

Though it switches the viewController but it prints blank. What's wrong with the code?

Upvotes: 0

Views: 593

Answers (2)

Tanuj
Tanuj

Reputation: 531

Working fine for me

-(IBAction)go:(id)sender
{
SecondViewController *secondVC = (SecondViewController *)[self.tabBarController.viewControllers objectAtIndex: 1];
    secondVC.itemText=@"Demo Text";
    self.tabBarController.selectedIndex=1;
}

Upvotes: 0

Michael Dautermann
Michael Dautermann

Reputation: 89549

My guess is that your first view controller's "secondController" property is not the same object pointed to in the tab bar controller.

The correct thing to do is to access your "SecondViewController" from the view controller array property in the tab bar.

That is to say, something like this:

-(IBAction)go:(id)sender
{
    SecondViewController *secondVC = (SecondViewController *)[self.tabBarController.viewControllers objectAtIndex: 1];
    secondVC.itemText=@"Demo Text";
    self.tabBarController.selectedIndex=1; 
}

Upvotes: 1

Related Questions