I have this:
NSMutableDictionary *responseDict = [responseString objectFromJSONString];
NSLog(#"%#" , [responseDict objectForKey:#"loginid"]);
and i want to put my "loginid" to NSUserDefault..
how to put the loginid value to NSUserDefault, and Retrieve ?
i tried this way but not working properly
[defaults setInteger:[responseDict objectForKey:#"loginid"] forKey:#"user_id"];
Please need help
thanks in advance
To put in NSUserDefaults you can do this
For saving:
NSString *logInId = [NSString stringWithFormat:#"%#",[responseDict objectForKey:#"loginid"]];
NSUserDefaults *preferences = [NSUserDefaults standardDefaults];
[preferences setValue:logInId forKey:#"logInId"];
[preferences synchronize];
For retrieving:
NSUserDefaults *preferences = [NSUserDefaults standardDefaults];
NSString *logInIdValue = [preferences valueForKey:#"logInId"];
Related
I am storing UIImage in NSMutableArray then storing NSMutableArray into NSDictionary.
Key of NSDictionary is a foldername and value of NSDictionary is a NSMutableArray.
Now how can i store and retrieve NSDictionary in NSUserDefaults.
I have done as follows:
NSMutableArray *imageArray=[[NSMutableArray alloc] init];
[imageArray addObject:selectedImage];
[allFolderWithImageDict setValue:imageArray forKey:#"UniqueFolderName"];
NSUserDefaults *defauktCenter = [NSUserDefaults standardUserDefaults];
[defauktCenter setValue:allFolderWithImageDict forKey:#"FolderImageDict"];
[defauktCenter synchronize];
But NSDictionary is not saving in NSUserDefaults.
Please suggest with some example
thanks
To Store and Retrieve Values of Custom Objects, you can use NSKeyedArchiver and NSKeyedUnarchiver Classes :
// To Save. . .
NSData *resData = [NSKeyedArchiver archivedDataWithRootObject:allFolderWithImageDict];
[[NSUserDefaults standardUserDefaults] setObject:resData forKey:#"FolderImageDict"];
// To Load. . .
NSData *respData = [[NSUserDefaults standardUserDefaults] objectForKey:#"FolderImageDict"];
resultDictionary = [NSKeyedUnarchiver unarchiveObjectWithData:respData];
NSLog(#"dict :: %#",resultDictionary);
GoodLuck !!!
To store UIImage objects in NSUserDefaults you need to a category implementation for UIImage that implements NSCoding protocol
here is one:
https://code.google.com/p/iphonebits/source/browse/trunk/src/Categories/UIImage-NSCoding.h
https://code.google.com/p/iphonebits/source/browse/trunk/src/Categories/UIImage-NSCoding.m
from
http://iphonedevelopment.blogspot.it/2009/03/uiimage-and-nscoding.html
Instead of using NSDictionary, use NSMutableDictionary.... :)
And to retrieve the data stored in dictionary.....
NSUserDefaults *d = [NSUserDefaults standardUserDefaults];
NSString *loadname1 = [d objectForKey:#"FolderImageDict"];
NSLog(#"%#", loadname1);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I reset the NSUserDefaults data in the iPhone simulator?
In my project i am saving some values in NSUserdefaults with different keys.And i have reset button in my app when i click that button values stored in user defaults should remove.Is there any way to delete those values without keys,and is addSuitedNamed: and removeSuitedName can use in this scenario.
NSUserDefaults * myNSUserDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary * dict = [myNSUserDefaults dictionaryRepresentation];
for (id key in dict) {
//heck the keys if u need
[myNSUserDefaults removeObjectForKey:key];
}
[myNSUserDefaults synchronize];
or
[NSUserDefaults resetStandardUserDefaults];
[NSUserDefaults standardUserDefaults];
With a selector being called on a button click you can achieve the same using
- (IBAction)btnResetUserDefaultsPressed:(id)sender {
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary* dictUserDefaults = [userDefaults dictionaryRepresentation];
for (id akey in dictUserDefaults) {
[userDefaults removeObjectForKey:akey];
}
[userDefaults synchronize];
}
For the second part of your question asked , You would certainly find this useful.
You can reset the values of NSUserDefault using resetStandardUserDefaults.
Check this code:
[NSUserDefaults resetStandardUserDefaults];
[NSUserDefaults standardUserDefaults];
Also you can:
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
Or you can use:
NSUSerDefaults *default = [NSUserDefaults standardUserDefaults];
NSDictionary *dictionary = [default dictionaryRepresentation];
for (NSString *key in [dictionary allKeys])
{
[default removeObjectForKey:key];
}
[default synchronize];
I am having values stored in an array, and stored that array in NSUserDefault, then i need to update that array can i do so. If then how?
First retrieve the current data.
NSArray *tempNew = [[NSArray alloc]init];
tempNew = [storeData objectForKey:#"accounts"];
[tempArr addObjectsFromArray:tempNew];
Update:
[tempArr addObject:str];
[storeData setObject:tempArr forKey:#"accounts"];
NSUserDefaults is just as an NSDictionary, so you can use the same method of updating a dictionary by setting another object to the key value -setObject:forKey:.
for example when you try below code
NSUserDefaults *usr=[NSUserDefaults standardUserDefaults];
NSArray *arr= [NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:2], nil];
[usr setObject:arr forKey:#"num"];
NSLog(#"usr %#",[usr arrayForKey:#"num"]);
NSUserDefaults *usr1=[NSUserDefaults standardUserDefaults];
NSArray *arr= [NSArray arrayWithObjects:[NSNumber numberWithInt:2],[NSNumber
numberWithInt:3], nil];
[usr setObject:arr forKey:#"num"];
NSLog(#"user1 %#",[usr1 arrayForKey:#"num"]);
u will get
usr (
1,
2
)
usr1 (
2,
3
)
in console.
Just re-store the array in the user defaults and call synchronize.
So for example:
Store your array...
NSMutableArray *yourArray = .... // whatever you did to create your data
// store your data in the NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:yourArray forKey:#"myArray"];
[defaults synchronize];
... and then some other time somewhere in your app update it!
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// retrieve your data from the NSUserDefaults
NSMutableArray *yourArray = [defaults objectForKey:#"myArray"];
// edit the data, for example add some object.
[yourArray addObject:someNewObject];
// update the defaults
[defaults setObject:yourArray forKey:#"myArray"];
[defaults synchronize];
I would like to save Array/NSDictionary to NSUserDefaults but anything I try is just not working. Here is my code so please if you know how to do this, help me.
NSArray *oneArray = [NSArray arrayWithObjects:#"Radio One",nil];
NSDictionary *one = [NSDictionary dictionaryWithObject:oneArray forKey:#"Stations"];
NSArray *oneLinkArray = [NSArray arrayWithObjects:#"http://mobile.com:28000/",nil];
NSDictionary *oneLink = [NSDictionary dictionaryWithObject:oneLinkArray forKey:#"Stations"];
[data addObject:one];
[link addObject:oneLink];
The reason I need this is to put this station into favorites. So my thinking is to save these info in to NSUserDefaults and retrieve in favorites table.
Thanks and please any suggestion is welcomed and appreciated.
You can use something like this when you store everything into a dictionary
[[NSUserDefaults standardUserDefaults] setObject:link forKey:#"dictionary1"];
Or you can put everything into an array and store it like this
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"array1"];
You can access it again by using
NSDictionary * myDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:#"dictionary1"];
Typically adding an object into NSUserDefaults goes like this:
NSMutableDictionary *dictionaryToAdd = [[NSMutableDictionary alloc] init];
[dictionaryToAdd setObject:#"xyz" forKey:#"myKey"];
NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
[myDefaults setObject:dictionaryToAdd forKey:#"someKey"];
[myDefaults synchronize];
A few things on your code above though - you're adding stuff into 'data' and 'link' but I don't see those in your code, so I'm assuming those arrays exist somewhere.
To sum it up - declare an NSUserDefaults object, set objects into it like an NSDictionary, and then synchronize it to save data.
Additional code as requested:
//You have an array named arrayToAdd that has already been created
NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
[myDefaults setObject:arrayToAdd forKey:#"SomeKeyThatYouMakeUp"];
[myDefaults synchronize];
//You want to get the array out of NSUserDefaults
NSArray *mySavedArray;
NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
mySavedArray = [myDefaults objectForKey:#"SomeKeyThatYouMakeUp"];
I need to save User Name and Password in NSUserDefault. I am planning to place a round rect button in IB. On pressing of which the User name and Password would be saved in NSUserDefault, so that when user kills the application and tries to login again after some time, they do not need to enter their login details again.
Any help would be highly appreciated.
Thanks and best regards,
PC
For Saving Username and Password I will personally suggest to use Keychain as they are more safer than NSUserDefault in terms of security since Keychain stores data in encrypted form while NSUserDefault stores as plain text. If you still want to use NSUserDefault Here's the way
FOR SAVING
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:txtUsername.text forKey:#"userName"];
[prefs setObject:txtPassword.text forKey:#"password"];
[prefs synchronize];
FOR RETRIEVING
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *savedUsername = [prefs stringForKey:#"userName"];
NSString *savedPassword = [prefs stringForKey:#"password"];
Do not store plaintext passwords in user defaults, even if they are unimportant.
Use Keychain Services. The Generic Keychain Sample provides sample KeychainWrapper class, that can be used for reading and writing data into keychain with exactly the same setObject:forKey: interface as NSUserDefaults uses.
To Save:
[[NSUserDefaults standardUserDefaults] setValue:_Username forKey:#"Username"];
[[NSUserDefaults standardUserDefaults] setValue:_password forKey:#"password"];
[[NSUserDefaults standardUserDefaults] synchronize];
To Read:
NSString * _UserName = [[NSUserDefaults standardUserDefaults] stringForKey:#"Username"];
NSString * _password = [[NSUserDefaults standardUserDefaults] stringForKey:#"password"];
First off, I would not store the password in NSUserDefaults. I would rather use the keychain.
This is how you can save the username in NSUserDefaults:
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
[standardUserDefaults setObject:myString forKey:#"username"];
NSString* username = [standardUserDefaults objectForKey:#"username"];
On the other hand, an easy way to use the keychain is by using the SSKeychain class by Sam Soffes; in this case you would just say:
NSString* password = [SSKeychain passwordForService:#"YOUSERVICENAMEHERE" account:username];
[SSKeychain setPassword:password forService:#"YOUSERVICENAMEHERE" account:username];
You can store your credentials like this:
-(void)saveToUserDefaults:(NSString*)stringUserName pswd:(NSString*)strPassword
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:stringUserName forKey:#"UserName"];
[standardUserDefaults setObject:strPassword forKey:#"Password"];
[standardUserDefaults synchronize];
}
}
And you can retrive them like this:
-(NSArray*)retrieveFromUserDefaults
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
NSString *userName = (NSString*)[standardUserDefaults objectForKey:#"UserName"];
NSString *password = (NSString*)[standardUserDefaults objectForKey:#"Password"];
}
NSArray* credentials = [NSArray arrayWithObjects:userName, password, nil];
return credentials;
}
Cannot set NSUserDefaults field
Posted my code from link to stay assured that answer is still useful to community even if the above mentioned post is removed or deleted in future.
Code:
You can try this code. I am very sure that it will work for you.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *uid=#"1";
[defaults setObject:uid forKey:#"init_val"];
[defaults synchronize];
For Retrieving Data You Should Use The Following Code :
NSString *initVal=[[NSUserDefaults standardUserDefaults] valueForKey:#"init_val"];
OR
NSString *initVal=[[NSUserDefaults standardUserDefaults] objectForKey:#"init_val"];
EDIT:
If still it gives nil, then you can use the following code:
NSString *initVal=[NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults] valueForKey:#"init_val"]];
OR
NSString *initVal=[NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"init_val"]];
In the above link, you will find my answer and replace "init_val" in my code there with your "username" and "password" as keys
Hope this helps you.
Good Answers are already given But here is a clean way of Saving/Loading/Deleting User Credentials in the keychain. Consider this, you can create a separate class and include the following code:
.h
#import <Foundation/Foundation.h>
#interface KeychainUserPass : NSObject
+ (void)save:(NSString *)service data:(id)data;
+ (id)load:(NSString *)service;
+ (void)delete:(NSString *)service;
#end
.m
#import "KeychainUserPass.h"
#implementation KeychainUserPass
+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
return [NSMutableDictionary dictionaryWithObjectsAndKeys:
(__bridge id)kSecClassGenericPassword, (__bridge id)kSecClass,
service, (__bridge id)kSecAttrService,
service, (__bridge id)kSecAttrAccount,
(__bridge id)kSecAttrAccessibleAfterFirstUnlock, (__bridge id)kSecAttrAccessible,
nil];
}
+ (void)save:(NSString *)service data:(id)data {
NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
[keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(__bridge id)kSecValueData];
SecItemAdd((__bridge CFDictionaryRef)keychainQuery, NULL);
}
+ (id)load:(NSString *)service {
id ret = nil;
NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
[keychainQuery setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
[keychainQuery setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
CFDataRef keyData = NULL;
if (SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
#try {
ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
}
#catch (NSException *e) {
NSLog(#"Unarchive of %# failed: %#", service, e);
}
#finally {}
}
if (keyData) CFRelease(keyData);
return ret;
}
+ (void)delete:(NSString *)service {
NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
}
#end