iOS - 将数据从一个viewController传递到另一个在xib中使用tabBarController的数据

问题描述:

我有一个要求,我必须将一个字符串值从一个viewController传递到另一个按钮单击。我也需要使用tabBarController从当前viewController切换到secondViewController。我想:iOS - 将数据从一个viewController传递到另一个在xib中使用tabBarController的数据

FirstViewController.h

#进口 “SecondViewController.h”

@property(nonatomic, strong) SecondViewController *secondController; 

FirstViewController.m

-(IBAction)go:(id)sender 
{ 
    [email protected]"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); 
    } 

虽然切换的viewController,但它打印空白。代码有什么问题?

我的猜测是你的第一个视图控制器的“secondController”属性不是在标签栏控制器中指向的同一对象。

正确的做法是在标签栏中从view controller array property访问您的“SecondViewController”。

也就是说,这样的事情:

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

应用的破碎工作的罚款。获取错误: ' - [UINavigationController setitemText:]:无法识别的选择器发送到实例' – Poles 2015-04-01 06:08:07

+1

我放下了我的代码的第一个(和错误的)行,现在一切都应该是正确的。如果你在你的“go”行中设置了一个Xcode断点,你期望的视图控制器是“secondVC”吗? – 2015-04-01 17:42:20

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