【问题标题】:How to access the variable of a class instantiated in another class?如何访问在另一个类中实例化的类的变量?
【发布时间】:2013-04-16 03:04:03
【问题描述】:

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

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

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

然后我转到DashboardViewController 并输入:

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

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

【问题讨论】:

  • 您确定[serverOutput intValue] 正在返回一个非0 值吗?记录[serverOutput intValue]。注意字符串中的意外空格。
  • 注意:你应该在调用presentViewController之前设置newView.userId。此外,您的NSLog 应该是:NSLog(@"%d", userid);NSLog 已经处理字符串格式。
  • @rmaddy - 谢谢,我是 XCode 的新手,您的建议很有帮助!是的 [serverOutput intValue] 返回一个非 0 值,我不知道是不是因为它只有一个数字。您知道将字符串“serverOutput”转换为整数的更好方法吗?
  • 您现在知道您对newView.userId 的调用被设置为非零值。现在您需要确定为什么它记录为零。您的userId 的日志在DashboardViewController 的哪个位置?确保在 LoginViewController 中设置它后调用它。此外,将日志更改为打印出self.userId 而不仅仅是userId。看看有没有帮助。
  • @rmaddy- 是的,我现在得到了预期的输出。谢谢你的帮助! :)

标签: objective-c uiviewcontroller nsstring integer


【解决方案1】:

只需替换您的代码:

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中合成。

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

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]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 2012-05-21
    • 2018-04-09
    相关资源
    最近更新 更多