NSUserDefaults not saving properly
I'm new to programming and I have the following problem I was hoping someone could help with. I have an app that uses a loggin to access the main menu. I would like the app to store the users name (from the login screen) and use it within the program. If the user has already logged in they don't have to log in again, ever. I want the app to check if the user has logged in on start up and go开发者_StackOverflow directly to the menu menu if they have.
My problem is at present if they press the login button they go straight to main menu without entering login details. If they enter they name I can use their name within the app until the app is restarted and the info is gone.
OK here is my new code but I still have the same problem.
-(IBAction)LogInButton:(id)sender {
NSString *tempstr = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
if (tempstr.length == 0) {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:name.text forKey:@"username"];
[prefs synchronize];
[self showCorrectController];
ClubFindViewController *logView = [[ClubFindViewController alloc] initWithNibName:@"ClubFindViewController" bundle:nil];
[self presentModalViewController:logView animated:YES];
}
else {
MainMenuView *mainView = [[MainMenuView alloc] initWithNibName:@"MainMenuView" bundle:nil];
[self presentModalViewController:mainView animated:YES];
}
}
-(void)viewDidLoad {
[super viewDidLoad];
[self showCorrectController];
}
-(void)showCorrectController {
UIViewController *viewController = nil;
if ([self isLoggedIn]) {
viewController = [[MainMenuView alloc] init];
}
else {
viewController = [[ClubFindViewController alloc] init];
}
[self presentModalViewController:viewController animated:YES];
[viewController release];
viewController = nil;
}
-(BOOL)isLoggedIn {
return ![[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
}
Any help would be greatly appriecated. Thanks.
In -(IBAction)LogInButton:(id)sender {
You should check if they have entered text, If not, prompt again.
In your case if the user presses 'Login' without entering name, the 'username' value will have empty string and the login will go through.
精彩评论