如何将NSString从一个UIViewController传递给另一个UIViewController?

可能重复:
iOS – 将variables传递给视图控制器

我有两个ViewController(ViewController1和ViewController2),我想要传递一个string值以及从ViewController1到ViewController2的IBAction。 我正在尝试阅读ViewController2的ViewDidLoad方法中的NSString(*检查)值,但它返回一个空值。

帮助我,并提前致谢。

// ViewController1 @interface ViewController1 : UIViewController { IBOutlet UIButton *btn1; IBOutlet UIButton *btn2; NSString *check; } #import "ViewController.h" -(IBAction)buttonClicked:(id)sender { check = [[NSString alloc] init]; if (btn1.tag == 0) { check = @"foo"; NSLog(@"%@",check); } if (btn2.tag == 1) { check = @"bar"; NSLog(@"%@",check); } } 

在我的第二个视图控制器,

 #import <UIKit/UIKit.h> @class ViewController1; @interface ViewController2 : UIViewController { ViewController1 *viewCon; } @property(nonatomic,retain) ViewController *viewCon; //.m #import "ViewController2.h" #import "ViewController1.h" @synthesize viewCon, - (void)viewDidLoad { ViewController *myVC = [[ViewController alloc] init]; NSLog(@" Label %@",myVC.check); [super viewDidLoad]; } 

 -(IBAction)buttonClicked:(id)sender { //check = [[NSString alloc] init]; -- NO Need if (btn1.tag == 0) { check = @"foo"; NSLog(@"%@",check); } if (btn2.tag == 1) { check = @"bar"; NSLog(@"%@",check); } ViewController2 *obj = [[ViewController2 alloc] initWithNibName:@"ViewController2"]; [obj setCheck:check]; //push to ViewController2 [obj release]; 

}

在你的第二个视图控制器,

 #import <UIKit/UIKit.h> @interface ViewController2 : UIViewController { NSString *check; } @property (nonatomic, retain) NSString *check; //.m #import "ViewController2.h" @synthesize check; - (void)viewDidLoad { NSLog(@" Label %@",check); } 

使用ViewController2的实例将点数据从ViewController1传递给ViewController2,其次是点运算符:

在ViewController2中创build一个NSString * strCheck的属性,因为你想把数据传递给ViewController2。

现在在button的ViewController1的点击事件

 -(IBAction)buttonClicked:(id)sender { { ....... ....... ViewController2 *objViewController2 = [ViewController2 alloc] initWithNibName:@"ViewController2" bundle:nil]; objViewController2.strCheck = check; //ViewController1's value to ViewController2 } 

看到这个链接 –
iOS – 将variables传递给视图控制器 。
我已经给出了同样的答案。

你需要设置variables的@property@synthesized 。 更多检查链接。