2013-04-23 80 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]);