如何访问在另一个类中实例化的类的变量?
问题描述:
我有两个类:DashboardViewController
(具有整数变量'userid')和LoginViewController
。我实例化DashboardViewController
并从LoginViewController
设置值userid
,但是当我在DashboardViewController
中输出userid
的值时,它会打印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代替它的整数值。任何帮助将不胜感激。
答
只是替换你的代码:
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]);
你肯定'[SERVEROUTPUT的intValue]'返回一个非0值?记录'[serverOutput intValue]'。留意字符串中意外的空白。 – rmaddy 2013-04-23 03:11:34
注意:您应该在调用presentViewController之前设置'newView.userId'。另外,你的'NSLog'应该是:'NSLog(@“%d”,userid);'。 NSLog已经处理字符串格式。 – rmaddy 2013-04-23 03:12:59
@rmaddy - 谢谢,我是XCode的新手,你的建议帮了很大忙!并且是[serverOutput intValue]返回一个非0值,我不知道它是否只是一个数字。你知道将字符串'serverOutput'转换为整数的更好方法吗? – spatra 2013-04-23 03:48:07