如何访问在另一个类中实例化的类的变量?

时间:2013-04-23 03:03:53

标签: objective-c uiviewcontroller nsstring integer

我有两个类:DashboardViewController(具有整数变量'userid')和LoginViewController。我实例化DashboardViewController并从userid设置LoginViewController的值,但当我在userid中打印DashboardViewController的值时,会打印0 }。有人可以帮帮我吗?

这是我从DashboardViewController实例化LoginViewController的方式('serverOutput'是包含单个整数值的字符串:

DashboardViewController *newView = [[DashboardViewController alloc] init];
[self presentViewController:newView animated:YES completion:nil];
newView.userid = [serverOutput intValue];

然后我转到DashboardViewController并输入:

NSLog([NSString stringWithFormat:@"%d",userid]);

并打印0而不是它应该的整数值。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

只需替换您的代码:

DashboardViewController *newView = [[DashboardViewController alloc] init];
[self presentViewController:newView animated:YES completion:nil];
newView.userid = [serverOutput intValue];

通过此代码:

DashboardViewController *newView = [[DashboardViewController alloc] init];
newView.userid = [serverOutput intValue];
[self presentViewController:newView animated:YES completion:nil];

如果你还没有得到答案,那么还有另一种方法......

有一种简单的方法可以解决您的问题。只需在Appdelegate类中创建一个全局变量。我的意思是,在NSString中创建一个AppDelegate.h属性并合成它。

AppDelegate.h:

@property(nonatomic,retain)NSString *GlobalStr;

并在AppDelegate.m中进行综合。

现在在AppDelegate中创建LoginViewController的对象:

AppDelegate *obj = (AppDelegate*)[[UIApplication sharedApplication]delegate];
DashboardViewController *newView = [[DashboardViewController alloc] init];
obj.GlobalStr = [serverOutput intValue];
[self presentViewController:newView animated:YES completion:nil];

然后转到DashboardViewController并输入:

AppDelegate *obj = (AppDelegate*)[[UIApplication sharedApplication]delegate];
userid = [obj.GlobalStr intValue];
NSLog([NSString stringWithFormat:@"%d",userid]);