PDA

View Full Version : Using NSUserDefaults




matthew858
Apr 19, 2009, 04:37 AM
I am making an application that has an account linked to it. The first time the app is launched, the user enters their username and password. These details are then stored in NSStrings. What I want to do is, on launch, check whether the username string is empty or contains a username (if the app has launched before). I have the following code:

AppDelegate:

- (void)applicationDidFinishLaunching:(UIApplication *)application {

NSUserDefaults *twitterUsername = [NSUserDefaults standardUserDefaults];
username = [twitterUsername stringForKey:@"twitter username"];

if(username == nil) {
[self firstTimeWelcomeMessage];
}

[window addSubview:tabBarController.view];

}



After username and password entry:

username = usernameTextField.text;
password = passwordTextField.text;



How would I go about putting the variable "username" into the NSUserDefault Twitter Username and have it successfully recognise on start-up that there is something stored in Twitter Username?



robbieduncan
Apr 19, 2009, 04:51 AM
Did you read the documentation for NSUserDefaults (http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html)? Particularly the setObject:forKey: (http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html#//apple_ref/occ/instm/NSUserDefaults/setObject:forKey:) method?

matthew858
Apr 19, 2009, 05:18 AM
Thanks for that. I have established I need the following:

[setObject:(id)username forKey:(NSString *)twitterUsername];


Can I just put this on a new line after username has been declared?

robbieduncan
Apr 19, 2009, 05:21 AM
Thanks for that. I have established I need the following:

[setObject:(id)username forKey:(NSString *)twitterUsername];


Can I just put this on a new line after username has been declared?

I suggest you need to read up on basic Objective-C as that is nothing like a valid method call. You need to learn the basics of the language before you try and write an application.