2011-02-14 23 views
0

在我的項目中,我的第一個視圖是一個登錄視圖,並且我希望將用戶名例如轉換爲其他類。 我真的不知道我怎麼能在其他類中得到它,我在stackoverflow中搜索,沒有找到(我嘗試了幾件事,但它沒有工作) 我給你如何我試圖做到這一點:通過在Objective-C中的類訪問變量

login.h

@interface loginViewController:UIViewController <UITextfieldDelegate>{ 

    IBOutlet UITextField *usernameField; 
    IBOutlet UITextField *passwordField; 
    IBOutlet UIButton *loginButton; 
    NSString *user; 

} 
@property (nonatomic, retain) UITextField *usernameField; 
@property (nonatomic, retain) UITextField *passwordField; 
@property (nonatomic, retain) UIButton *loginButton; 
@property (nonatomic, retain) NSString *user; 
- (IBAction)login: (id) sender; 
- (NSString *)user; 

@end 

login.m

@implementation LoginViewController 

@synthesize usernameField; 
@synthesize passwordField; 
@synthesize loginButton; 

- (IBAction) login: (id) sender{ 
    user=[[NSString alloc ]initWithFormat:@"%@",usernameField.text]; 
    //...I put here my login code... 

    } 

- (NSString *)user{ 
    return user; 
    } 

home.m

@implementation homeViewController 
- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
user2 = LoginViewController.user ; //I tried this after the advice given below, still not working 
user2 = LoginViewController.usernameField.text; //same 

NSLog(@"user: %@",user2); 

} 

我將在我的所有項目中都需要此值,以顯示有關所連接客戶端的信息。

我只需要一個提示或我可以使用的示例代碼。

編輯:我改變了我的代碼下面給出的建議,告訴我,如果我錯過了什麼

回答

0

創建homeViewController類loginViewController的對象。

然後獲取或設置登錄變量的值,按您的需求量的。

假設你需要的NSString在homeViewController,創建homeViewController loginViewController的對象。

anyRequiredVariable=login.usernameField.text;//Assuming that login is the object of loginViewController Class. 

這將解決您的問題。

乾杯

+0

我試圖做像你說我,但似乎我不能像訪問我loginViewController,我仍然有一個錯誤(要求的東西不是一個結構或聯合成員「文」 ) 我試過了: userTest = LoginViewController.usernameField.text; 其中userTest是一個NSString。 告訴我,如果我錯過了什麼 – ciwol 2011-02-14 10:45:39

+0

它仍然無法與它的工作,我不知道該怎麼加 – ciwol 2011-03-01 08:22:40

1

兩件事情:

  1. 你的主要問題是,你宣佈採取sender參數(getUser:(id)sender)的方法,但沒有冒號或參數被髮送消息(getUser) 。這是完全不同的兩件事。

  2. 訪問者在Objective-C不應get開始 - 這意味着別的東西。選擇器(基本上是方法名稱的Objective-C術語)應該是user。所以:

    - (NSString *)user { 
        return user; 
    }