NSUser default is not saving any value - ios

I am trying to store userid coming from server to userDefaults which is a NSUserDefault object, but its always showing 0 for the value of userDefaults, I had tried using setObject method too but still its not working, and i have checked for informatioon coming from server its never a 0. value for user id is never 0 but still NSUserDefault is showin a 0 for it.
int userid=[[userdata objectForKey:#"id"] integerValue];
[userDefaults setInteger:userid forKey:#"UserID "];
[userDefaults synchronize];
NSLog(#"UID: %d",[[NSUserDefaults standardUserDefaults] integerForKey:#"UserID"]);
please help me thanks.

You are saving using the key #"UserId " note the space and reading using the key #"UserId" without an extra space.

As David Rönnqvist pointed out, you have a space in one of your keys but not in the other.
What I usually do is to #define all my user defaults keys in a file constants.h, and then use those constants instead of re-typing the string literal each time. This makes mistakes like yours impossible, and also makes it easier to keep track of the keys you are using.

you can try this way to store and retrieve data..
for set the value..
[[NSUserDefaults standardUserDefaults]setInteger:10 forKey:#"USERID"];
for retrieve the value..
NSLog(#"%d",[[[NSUserDefaults standardUserDefaults] valueForKey:#"USERID"]integerValue]);
good luck..

You can try this way
int userid=[[userdata objectForKey:#"id"] integerValue];
[userDefaults setInteger:userid forKey:#"UserID"];
[userDefaults synchronize];
NSLog(#"UID: %d",[[NSUserDefaults standardUserDefaults] integerForKey:#"UserID"]);
Happy coding........

Related

NSNotFound not working with NSUser default

As I am storing one Integer value into NSUserDefaults aas its used at many places. At first time its working fine but while i close my application and again open it I am check that user already selected any option in past feom NSUserDefaults stored value but I am failed in that
Some thing is wrong in my case
Here is my code for checking Integer value is there in userdefault :
NSInteger selectedBusinessUnit = [[NSUserDefaults standardUserDefaults] integerForKey:#"selectedUnit"];
if ( selectedBusinessUnit != NSNotFound){
//go to direct main screen.
}else {
// load Business unit screen for selection.
}
But its always found value even i am deleting app and reinastall it.
Always my selected value is 0.
Let me know what is my silly mistake here.
Edit:
[[NSUserDefaults standardUserDefaults] setInteger:sender.tag forKey:#"selectedUnit"];
[[NSUserDefaults standardUserDefaults] synchronize];
THNAKS .
Obviously there is a misunderstanding: NSNotFound is not equal to key is missing, it's a valid integer value.
The easiest way to keep your logic is to register the key-value pair with NSNotFound as the default value.
As soon as possible (applicationDidFinishLaunching or earlier) write
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *defaultValues = #{#"selectedUnit": #(NSNotFound)};
[defaults registerDefaults:defaultValues];
That means NSNotFound is considered as default value until it's overwritten the first time. The 3 lines must be executed every time the application launches. If the app is reinstalled the default value is taken again.
Now you can use your logic in the question.
PS: You don't need to synchronize after writing. The framework does that periodically.
The default value for integer is 0, according to the documentation:
-integerForKey: is equivalent to -objectForKey:, except that it converts the returned value to an NSInteger. If the value is an
NSNumber, the result of -integerValue will be returned. If the value
is an NSString, it will be converted to NSInteger if possible. If the
value is a boolean, it will be converted to either 1 for YES or 0 for
NO. If the value is absent or can't be converted to an integer, 0 will
be returned.
if you want to check if a key exists in NSUserDefaults use:
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"selectedUnit"] != nil)
{
...
}
NSUserDefaults storage only object, NSNumbers.
I think the problem in conversion from NSNumber, which you stored to integer in method integerForKey.
Another case - may be you forgot a synchronize NSUserDefaults.
You can set object like
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:#(yourIntegerValue) forKey:#"yourIntegerKey"];
[userDefaults synchronize];
and you can check like this
NSNumber *integerValue = [userDefaults objectForKey:#"yourIntegerKey"];
if (integerValue) {
//
}

Finding recurring items in NSUserDefaults

I am having a hard time understanding how to go about finding the values that repeat more than once. I'm just not understanding from the code below how to go about getting the duplicate values. thanks for any help!!
[appDelegate.scannedNumbers addObject:result];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:appDelegate.scannedNumbers forKey:#"scannedNumbers"];
[userDefaults synchronize];
[BT_debugger showIt:self message:[NSString stringWithFormat:#"After writing scannedNumbers: %#" [[NSUserDefaults standardUserDefaults] objectForKey:#"scannedNumbers"]]];
Setting a default has no effect on the value returned by the objectForKey: method if the same key exists in a domain that precedes the application domain in the search list.
Apple Documentation
You have to check if the key already exists before you will set another object for the same key.

registerDefaults method sets the default value not the actual value.?

I want to understand the functionality of,
[NSUserDefaults standardUserDefaults] registerDefaults:];
Does registerDefaults method set the default value and not the actual value. For example, assuming i execute the following statements in sequence,
[[NSUserDefaults standardUserDefaults] setObject:#"1" ForKey:#"test"];
and then call,
[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:#"2",#"test", nil]];
I see that valueForKey test is still 1 and not 2.
Could someone provide me a better understanding of registerDefaults or is my above anology right?
If my anology is right,then does it mean that the default value is picked up only when no object is set for that specific key?
Thanks in advance.
Does registerDefaults method set the default value and not the actual value
Yes. The value that you pass in the dictionary to registerDefaults: is returned to you only when there is no specific value set for that key.
When you set the value #"1" for the key #"test", you "hide" the default value registered in the registerDefaults: call.
If you do this
[NSUserDefaults standardUserDefaults] registerDefaults:#{#"a":#"1", #"b":#"2"}, nil]];
[[NSUserDefaults standardUserDefaults] setObject:#"200" ForKey:#"b"]; // Override
and then request the values for keys #"a" and #"b", you get the default value #"1" for #"a" and the specific value of #"200" for #"b".

nsuserdefault has key-values set how to delete it?

I have already tried to delete all the key-values pair when the app starts and again when i check keys these keys are saved in NSUserDefault. I have these preferences stored.
NSArray *keys = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys];
NSLog(#"all keys %#", keys);
keys (
NSLanguages,
AppleITunesStoreItemKinds,
AppleLocale,
AppleLanguages,
NSInterfaceStyle
)
When I store new dynamic values to the NSUserDefaults, I want to select all the keys except these preferences.
Please help me with this problem.
Thanks in advance
Don't do what you're trying to do. Don't tamper with any of the keys added by Apple. Keep your own set of keys (preferably with prefixes on the names) and edit only those.
Generally you shouldn't delete keys unless there is some specific requirement in your app to do so. What you should do is to set default values for each of your keys when the app starts:
[[NSUserDefaults standardUserDefaults] registerDefaults:#{... : ...}];
These defaults will be valid while the app is running but won't be saved. If you set anything using any of the set...:forKey: methods and synchronize then they will overwrite the defaults and be saved.
Try this
- (NSDictionary *) dictionaryRepresentation. Using this method on the standard user defaults, you can get a list of all keys in the user defaults. You can then use this to clear the user defaults:
NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
NSDictionary * dict = [defs dictionaryRepresentation];
for (id key in dict) {
[defs removeObjectForKey:key];
}
[defs synchronize];
removeObjectForKey -- that should give you the ability to remove a preference.
You can remove everything in NSUserDefaults associated with your app by calling this.
// remove entire user defaults
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
[[NSUserDefaults standardUserDefaults] synchronize]; // not sure if needed, but never hurts
This should give you a clean slate for saving information to user defaults.

Add object to existing key in NSuserDefault

I want to add the another object to existing key in NSUserDefault.
I try this code to add in NSUserDefault.
delegate.str=[first objectAtIndex:delegate.selectId];
NSLog(#"%#",delegate.str);
delegate.str1=[details1 objectAtIndex:delegate.selectId];
NSLog(#"%#",delegate.str1);
[delegate.BookMarkDefault setObject:delegate.str forKey:#"Name"];
// BookMarkDefault This is NSUSERDefault.
First I will insert delegate.str value value successfully goes to NSUSerDefault, but when next time adding new value through delegate.str for key under Name will replace previous value. I want to add new value under the same Key.
This is not possible if you want to fullfill this kind of requirement then try to use array and then put that array into NSUSerDefault...
Try this code
delegate.str=[first objectAtIndex:delegate.selectId];
NSLog(#"%#",delegate.str);
delegate.str1=[details1 objectAtIndex:delegate.selectId];
NSLog(#"%#",delegate.str1);
[yourarray addObject:delegate.str];
NSLog(#"%#",delegate.Bookmarknamearray);
[delegate.BookMarkDefault setObject:youarray forKey:#"Name"];
No its not possible to assign multiple values to same key. If you want to use multiple values to same key then use array or dictionary and assign them to the key.
Ex :
[[NSUserDefaults standardUserDefaults] setObject:YOUR_ARRAY forKey:#"Name"];
Hope it helps you.
You can't save two objects for same key.In NSUserDefaults and NSDictionary keys will be unique (There can be only one object for a particular key).
If you need to do this, you can store the values in NSMutableArray or NSDictionary and add that to the NSUserDefaults like:
[[NSUserDefaults standardUserDefaults] setObject:dataArray forKey:#"Name"];
It may be helpful
[[NSUserDefaults standardUserDefaults] setObject: delegate.str forKey:#"Name"];
You can not assign two value in single key of NSUserDefaults, you must need to take another "KEY" for each value . your can replace pervious value by using following code :
Just try with following code :
[[NSUserDefaults standardUserDefaults] setObject: delegate.str forKey:#"Name"];
EDITE:
But you can add array in NSUserDefaults, suchlike
self.golbalArr = [[NSMutableArray alloc]initWithObject:#"1", #"2",....,nil];
[[NSUserDefaults standardUserDefaults] setObject: self.golbalArr forKey:#"Name"];

Resources