2013-04-23 90 views
1

我有两个类:DashboardViewController(具有整数变量'userid')和LoginViewController。我实例化DashboardViewController并从LoginViewController设置值userid,但是当我在DashboardViewController中输出userid的值时,它会打印0。有人能帮助我吗?如何访问在另一个类中实例化的类的变量?

这是我的实例DashboardViewControllerLoginViewController( 'SERVEROUTPUT' 是包含一个整数值的字符串:

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

然后我去DashboardViewController并提出:

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

这版画0代替它的整数值。任何帮助将不胜感激。

+3

你肯定'[SERVEROUTPUT的intValue]'返回一个非0值?记录'[serverOutput intValue]'。留意字符串中意外的空白。 – rmaddy 2013-04-23 03:11:34

+2

注意:您应该在调用presentViewController之前设置'newView.userId'。另外,你的'NSLog'应该是:'NSLog(@“%d”,userid);'。 NSLog已经处理字符串格式。 – rmaddy 2013-04-23 03:12:59

+0

@rmaddy - 谢谢,我是XCode的新手,你的建议帮了很大忙!并且是[serverOutput intValue]返回一个非0值,我不知道它是否只是一个数字。你知道将字符串'serverOutput'转换为整数的更好方法吗? – spatra 2013-04-23 03:48:07

回答

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类中创建一个全局变量。我的意思是,在AppDelegate.h中制作NSString财产并对其进行合成。

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]); 
相关问题