Objective c 如何访问在另一个类中实例化的类的变量?
我有两个类:Objective c 如何访问在另一个类中实例化的类的变量?,objective-c,uiviewcontroller,nsstring,integer,Objective C,Uiviewcontroller,Nsstring,Integer,我有两个类:DashboardViewController(具有整数变量“userid”)和LoginViewController。我实例化了一个DashboardViewController并从LoginViewController设置了userid的值,但是当我在DashboardViewController中打印userid的值时,它会打印0。有人能帮我吗 这就是我如何从LoginViewController实例化DashboardViewController(“serverOutput”
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];
然后,我转到仪表板视图控制器并放置:
NSLog([NSString stringWithFormat:@"%d",userid]);
AppDelegate *obj = (AppDelegate*)[[UIApplication sharedApplication]delegate];
userid = [obj.GlobalStr intValue];
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
中合成它
现在在LoginViewController
中创建AppDelegate
的对象:
AppDelegate *obj = (AppDelegate*)[[UIApplication sharedApplication]delegate];
DashboardViewController *newView = [[DashboardViewController alloc] init];
obj.GlobalStr = [serverOutput intValue];
[self presentViewController:newView animated:YES completion:nil];
然后转到仪表板视图控制器
,并放置:
NSLog([NSString stringWithFormat:@"%d",userid]);
AppDelegate *obj = (AppDelegate*)[[UIApplication sharedApplication]delegate];
userid = [obj.GlobalStr intValue];
NSLog([NSString stringWithFormat:@"%d",userid]);
您确定
[serverOutput intValue]
正在返回非0值吗?日志[serverOutput intValue]
。请注意字符串中的意外空白。注意:在调用presentViewController
之前,您应该设置新视图.userId
。此外,NSLog
应该是:NSLog(@“%d”,userId);
NSLog
已经可以处理字符串格式了。@rmaddy-谢谢,我是XCode新手,你的建议帮了我很大的忙!是的[serverOutput intValue]返回一个非0值,我不知道它是否为零,因为它只是一个数字。您知道将字符串“serverOutput”转换为整数的更好方法吗?现在您知道对newView.userId的调用被设置为非零值。现在您需要确定为什么它记录为零。在DashboardViewController 您的userId
日志吗?请确保在您的LoginViewController
中设置后调用它。另外,将日志更改为打印出self.userId
,而不仅仅是userId
。看看这是否有帮助。@rmaddy-是的,我现在得到了预期的输出。谢谢您的帮助!:)