我有两个类: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而不是它应该的整数值。任何帮助将不胜感激。
答案 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]);