Iphone 在ios中如何将变量从一个控制器传递到另一个控制器?
我有一个控制器,变量如下Iphone 在ios中如何将变量从一个控制器传递到另一个控制器?,iphone,objective-c,ios,Iphone,Objective C,Ios,我有一个控制器,变量如下 NSString *str; 在同一个控制器中,我正在字符串str中分配userId 我需要在另一个控制器中显示用户数据 如何在另一个控制器中获取userId的值 下面是我的代码: MainViewController.h @property (nonatomatic) NSString *str; @property(nonatomatic, retain) MainViewController *mainCon; MainViewController.m @s
NSString *str;
在同一个控制器中,我正在字符串str
中分配userId
我需要在另一个控制器中显示用户数据
如何在另一个控制器中获取userId
的值
下面是我的代码:
MainViewController.h
@property (nonatomatic) NSString *str;
@property(nonatomatic, retain) MainViewController *mainCon;
MainViewController.m
@synthesize str;
str = 1;
@synthesize mainCon;
NSLog(@"user id is %@", mainCon.str);
现在进入FirstViewController.h
@property (nonatomatic) NSString *str;
@property(nonatomatic, retain) MainViewController *mainCon;
FirstViewController.m
@synthesize str;
str = 1;
@synthesize mainCon;
NSLog(@"user id is %@", mainCon.str);
在日志中,我得到了空值。在MainVC中获取一个属性,并从FirstVC传递值,然后它将为您工作 以下代码必须在MainVC中
@property (strong, nonatomic) NSString *str;
@synthesize str;
在FirstVC中
MainVC * vc = [[MainVC alloc]init];
vc.str = @"test";
步骤1: 您必须创建一个视图控制器类作为常量 第二步: 您可以在Constanst类中删除.m文件 第三步: 您必须导入Projectname_Prefix.pch中的Constants.h,它将是其他资源文件夹中的xcode。现在常量类将充当全局类 步骤4:
现在,您可以在Constants.h中声明变量。Constants.h中声明的变量将作为全局变量。您可以在任何地方访问它。您的最佳选择是使用[prepareForSegue]方法 在这种方法中,我通常有
if ([segue.identifier isEqualToString@"segueName"]){
//I use this if statement to check which segue I am performing, if I have multiple
//segues from a single view controller
FirstVc *newViewController = segue.destinationViewController;
newViewController.str = self.str;
}
这将把字符串从主VC传递到新VC。这都是假设您的转换是在Interface Builder中布置的,或者以某种方式允许您访问序列和标识符
SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
secondViewController.str1 = str;
[self.navigationController pushViewController:secondViewController animated:YES];
这是一个更快、更简单的解决方案。您在哪里分配了firstViewController