How to remove user defaults [duplicate] - iphone

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];

Related

iphone xcode 5 app iOS

How I can save value in TextField for showing after closing and opening app?
self.suma.text = [NSString stringWithFormat:#"%d", [self.a1.text intValue]+[self.a2.text intValue]];
I want to do it with "suma".
See documentation for NSUserDefaults.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// Write
[defaults setObject:self.suma.text forKey:#"suma"];
// Read
self.suma.text = [defaults stringForKey:#"suma"];

retrieve values from NSUserDefault in iPhone after setting again

In App delegate, I have following code:
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
NSString *alrmTime = #"10:00 AM";
[pref setObject:alrmTime forKey:#"alarmTime"];
[prefs synchronize];
From here I am getting from App delegate User Daeault in Controller A using code
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *tempAlarmTime = [defaults stringForKey:#"alarmTime"];
cell.textLabel.text = [NSString stringWithFormat:#"Remind At %#", tempAlarmTime];
Now, I need to set this userdefault in Controler B , For this m using this:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:mTimeIntervalSTR forKey:#"alarmTime"];
[prefs synchronize];
Now when I need to get this new value in Controller A its coming Null. Why this is happening, and how will I get new set value?
in Controler B use the following to change the userdefault value
NSString *timeString =[[[NSUserDefaults standardUserDefaults] objectForKey:#"alarmTime
"]mutableCopy];
timeString = mTimeIntervalSTR;
[[NSUserDefaults standardUserDefaults]setObject:timeString
forKey:#"alarmTime "];
[[NSUserDefaults standardUserDefaults]synchronize];
After adding a value, call [[NSUserDefaults standardUserDefaults] synchronize];.

How to save User Name and Password in NSUserDefault?

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

How to keep my data in a array-iphone sdk

I'm trying to create an application, and in that I'm receiving some contents from net and loading into and array, if I quit and run the app again i'm losing the data. How can I store the data in the app itself. Should I use some kind of database? If so which one and how can I implement that? I need to store only some string variables.
EDIT:
My app is tabbar based app, and have two tabs. Loading the arrays in one tab and loading that array in a table in the other VC. once I load the array and move to the second tab, the table is loaded with the array. If i go back and add few more values and then if i check, the added datas is not displayed in the table. And also, when I quit the app the table lose all the values, I need to keep the values in the table, even after i quit the app. How can I do that?
here is my code:
in viewdidload:
NSUserDefaults *simplePlistDb = [NSUserDefaults standardUserDefaults];
[simplePlistDb setBool:YES forKey:#"isItWorking"];
[simplePlistDb setObject:alertList forKey:#"myArray"];
[simplePlistDb synchronize];
in cellforrowatindexpath:-
NSUserDefaults *simplePlistDb = [NSUserDefaults standardUserDefaults];
BOOL flag = [simplePlistDb boolForKey:#"isItWorking"];
if (flag)
{
NSArray *myArray = [simplePlistDb objectForKey:#"myArray"];
for (NSString *str in myArray){
NSLog(#"Str:%#", str);
[loadArray addObject:str];
}
cell.textLabel.text = [loadArray objectAtIndex:indexPath.row];
}
Thank you.
You will want to look into Core Data if you want to save a decent amount of data to the iPhone. However, if not, you can just load the items in the array into a plist and load them from there at launch.
Plist Writing: How to create a new custom property list in iPhone Applications
CoreData: http://www.raywenderlich.com/934/core-data-tutorial-getting-started
Edit--->
As Nekto said, you can also use NSUserDefaults, but I advise mainly using NSUserDefaults for simple NSStrings and integers.
I think for your purposes NSUserDefaults will be enough : NSUserDefaults Class Reference.
Examples:
// save
NSUserDefaults *simplePlistDb = [NSUserDefaults standardUserDefaults];
[simplePlistDb setBool:YES forKey:#"isItWorking"];
[simplePlistDb setObject:[NSArray arrayWithObjects:#"very", #"cool", nil]];
[simplePlistDb synchronize];
// restore
NSUserDefaults *simplePlistDb = [NSUserDefaults standardUserDefaults];
BOOL flag = [simplePlistDb boolForKey:#"isItWorking"];
if (flag)
{
NSArray *myArray = [simplePlistDb objectForKey:#"myArray"];
for (NSString *str in myArray)
NSLog(#"%#", str);
}
You can use NSUserDefaults in order to store your data till the time your app is installed in your device.
How to write in NSuserDefaults:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"yourObject1" forKey:#"correspopndingKey1"];
[defaults setObject:#"yourObject2" forKey:#"correspopndingKey2"];
[defaults synchronize];
How to read from NSuserDefaults:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *temp1 = [defaults objectForKey:#"correspopndingKey1"];
NSString *temp2 = [defaults objectForKey:#"correspopndingKey2"];
You can store NSArray in a similar way.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:objArray forKey:#"correspopndingKey"];
[defaults synchronize];

problem in saving a value in iphone

when i enter a value in the iphone simulator and press the save button it only keeps the value until the simulator is running. and when i restart the simulator and press the load button it shows an earlier value entered by me.i.e, it is not able to keep the new value and keeps only old value.
i am using following loops for saving a file and loading a file.
-(IBAction) save{
NSUserDefaults *sinner=[NSUserDefaults standardUserDefaults];
[sinner setObject:serverIP.text forKey:#"load"];
NSUserDefaults *king=[NSUserDefaults standardUserDefaults];
[king setObject:noc.text forKey:#"save"];
}
-(IBAction) load {
NSUserDefaults *sinner=[NSUserDefaults standardUserDefaults];
NSString *tempstring =[sinner stringForKey:#"load"];
serverIP.text = [NSString stringWithFormat:tempstring];
NSUserDefaults *king=[NSUserDefaults standardUserDefaults];
NSString *tempstring1 =[king stringForKey:#"save"];
noc.text = [NSString stringWithFormat:tempstring1];
}
// Your code
NSUserDefaults *king= [NSUserDefaults standardUserDefaults];
[king setObject:bookmarks forKey:#"Bookmarks"];
// saving it all
[king synchronize];
-(IBAction) save{
NSUserDefaults *sinner=[NSUserDefaults standardUserDefaults];
[sinner setObject:serverIP.text forKey:#"load"];
[sinner setObject:noc.text forKey:#"save"];
[sinner synchronize];
}
This should save the contents. You dont need two separate userdefaults. To load them you can try
-(IBAction) load {
NSUserDefaults *sinner=[NSUserDefaults standardUserDefaults];
NSString *tempstring =[sinner stringForKey:#"load"];
serverIP.text = tempstring;
NSString *tempstring1 =[sinner stringForKey:#"save"];
noc.text = tempstring1;
}
Hope this helps