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 connec开发者_如何学JAVAted.
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:
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.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 beuser
. 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
精彩评论