简体   繁体   中英

Access variable through classes in objective-c

In my project, my first view is a loging one, and I would like to get the username for example into others classes. I don't really know how I can get it in other classes, I searched in stackoverflow and didn't find (I tried several things but it didn't work) I give you how I tried to do this:

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

}

I will need this value in all of my project, to display the informations about the client which is connected.

I just need a tip or a sample code I can work with.

Edit: I changed my code following the advices given, tell me if I missed something

Two things:

  1. Your main problem is that you declared a method that takes a sender argument ( getUser:(id)sender ), but are sending a message with no colon or arguments ( getUser ). Those are two totally different things.

  2. Accessors in Objective-C should not start with get — it means something else. The selector (which is basically the Objective-C term for method names) should just be user . So:

     - (NSString *)user { return user; } 

Create an object of your class loginViewController in homeViewController.

Then get or set the value of the login variable as per your requirment.

Assuming that you need a NSString in your homeViewController,Create an object of loginViewController in homeViewController.

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

This will solve your problem.

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM