Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store values in NSUserDefaults like as a Database?

I need to create an application using NSUserDefaults.

In my first view I will enter the password. In second view I will enter the confirm password. Then validation will happen; after then if password will be match in both views, then success window will open. After then some views will come. I need that password should be save in NSUserDefaults for future use.

If I will close my application after validation, then if I will build and run again my application now the password validation window should not be open.

Only one view simply will ask the password, if the current password is equal to before terminate application's password, then the application's success view will be open. Now here the validation should be compare with current password with NSUserDefaults's value[i.e old password, which is stored before terminate my application].

It is possible to using NSUserDefaults?

like image 759
Velmurugan Avatar asked Nov 24 '10 18:11

Velmurugan


2 Answers

Objective-C:

To save in Defaults

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];

To retrieve

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];

Swift:

var userDefaults : NSUserDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject("TextToSave", forKey: "keyToLookupString")
//To retrieve
let mySavedObject = userDefaults.objectForKey(@"keyToLookupString")

Anyway just a hint do not store passwords in NSUserdefaults. Use keychain for storing secure data.

like image 129
ipraba Avatar answered Nov 06 '22 13:11

ipraba


Do not use NSUserDefaults to hold user passwords! It is not secure. You should store passwords in the keychain where it is encrypted, there's small wrapper class that makes saving username/password into the keychain very easy:

http://log.scifihifi.com/post/55837387/simple-iphone-keychain-code

like image 8
Kendall Helmstetter Gelner Avatar answered Nov 06 '22 12:11

Kendall Helmstetter Gelner