NSUserDefaults Contains Value Or Not? - ios

How to know whether NSUserDefaults contains any value?How to check whether its empty?

There isn't a way to check whether an object within NSUserDefaults is empty or not.
However, you can check whether a value for particular key is nil or not.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSObject * object = [prefs objectForKey:#"your_particular_key"];
if(object != nil){
//object is there
}

NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *string = [data objectForKey:#"yourKey"];
if(string==nil)
NSlog(#"nil")
Take a look at NSUserDefault documentation
// For saving the values
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
// saving an NSString
[userDefaults setObject:#"Ttest" forKey:#"key"];
// --- For Retrieving
NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [userDefaults stringForKey:#"key"];

To check whether a specific value is set or not, no matter of its location (global or application's), check the returned value of -[NSUserDefaults objectForKey:]
id obj = [[NSUserDefaults standardUserDefaults] objectForKey:#"My-Key-Name"];
if (obj != nil) {...}
To check if the application (bundle) has any settings stored in user defaults:
NSUserDefaults* sdu = [NSUserDefaults standardUserDefaults];
NSString* bundleId = [[NSBundle mainBundle] bundleIdentifier];
NSDictionary* mainBundleSettings = [sdu persistentDomainForName:bundleId];
NSLog(#"%#", mainBundleSettings);
If you are interested in all possible values for which -[NSUserDefaults objectForKey:] will return something, including system global settings, simply call
NSDictionary* allPossibleSettings = [sdu dictionaryRepresentation];
NSUserDefaults is never empty. It combines global settings, bundle's settings, temporary data and maybe something else. For example, if you call:
[[NSUserDefaults standardUserDefaults] objectForKey:#"NSBoldSystemFont"]
you will get the #"LucidaGrande-Bold" string value which will be taken from global settings, even when your application has never set this value.

Related

How to transfer new int value and save previous int value?

I used
NSString *level =[[NSUserDefaults standardUserDefaults] stringForKey:#"Key"];
But this method may contain only one value.
How to transfer new int value and save previous int value?
A key can only have one value.
If you want to save a previous value, use a new key.
I'd recommend "oldKey" or "previousKey" in your user defaults to indicate the previous value. E.G.:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *oldLevel = [defaults stringForKey: #"Key"];
[defaults setObject: oldLevel forKey: #"PreviousKey"];
[defaults setObject: newLevel forKey: #"Key"];

`[NSUserDefaults standardUserDefaults]` returns nil

I want to save some user preferences, but
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
just returns nil.
iOS-Developper Library says, that this should return the existing shared defaults object or create one if none exists... What am I missing?
I also use Appirater and there all this stuff seems also not to work...
This code gets called when the user pushes a button...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int index = ([defaults integerForKey:#"BackgroundColorSpecifier"]+ 1)%self.backgroundColors.count;
[defaults setInteger:index forKey:#"BackgroundColorSpecifier"];
[defaults synchronize];
This gets called in application: didFinishLaunchingWithOptions:
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
[standardDefaults registerDefaults:#{#"BackgroundColorSpecifier": #0}];
[standardDefaults synchronize];
When I debug this code snippets the green "position-indicator" jumps around in a very strange manner...
I don't have any clue, whats going on... Please help!
This is far more likely to be a problem with the debugger than anything else, particularly with your other issues. I've seen similar things in my own projects but don't have a reliable way of clearing it out other than the usual restart / clean options.
NSLogs will usually give more consistent results than the debugger if the debugger is having an off day.
NSUserDefaults isn't broken. We'd have heard about it by now.
you can use this function to log you userDefaults dic
- (void)logCache
{
NSDictionary * dic = [[NSBundle mainBundle] infoDictionary];
NSString *bundleId = [dic objectForKey: #"CFBundleIdentifier"];
NSUserDefaults *appUserDefaults = [[NSUserDefaults alloc] init];
NSDictionary *cacheDic = [appUserDefaults persistentDomainForName: bundleId];
NsLog(#"cacheDic::%#",cacheDic);
}

Set switch position to ON by first app launch using NSUserDefaults

I have switches in my app that stores position by standardUserDefaults, but when app starts for first time all my switches are in OFF position. How can I set them to ON by default?
Save
NSUserDefaults *defs1 = [NSUserDefaults standardUserDefaults];
[defs1 setBool: blackSwitch.on forKey: #"blackKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
Load
NSUserDefaults *defs1 = [NSUserDefaults standardUserDefaults];
blackSwitch.on = [defs1 boolForKey: #"blackKey"];
First of all
Do the following
NSUserDefaults *defs1 = [NSUserDefaults standardUserDefaults];
BOOL isOn = [defs1 boolForKey: #"blackKey"];
if(isOn) NSLog(#"isOn");
Second asure that blackSwitch is not nil
if(blackSwitch) NSLog(#"blackSwitch is not nil");
If blackswitch is nil, that means that you are still in early stage of view controller initialization, you should move the code that sets it on to viewDidLoad or viewWillAppear
For setting default values please use this code
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSNumber *testValue = [NSNumber numberWithBool:YES];
NSDictionary *appDefaults = [[NSDictionary alloc] initWithObjectsAndKeys:
testValue, #"blackKey", nil];
[defaults registerDefaults:appDefaults];
[appDefaults release];
Use the NSUserDefaults method registerDefaults to pass a default value of 'true' along with your #"blackKey" key. This will ensure that #"blackKey" is set to ON until the user makes a change to it themselves.

How to set initial values for NSUserDefault Keys?

I want to set some initial values for my NSUserDefault keys so that the first run of the app has some reasonable initial settings. I thought I ran across a simple way to do this in the app bundle .plist, but now I can't find it. Any ideas?
You should use the registerDefaults method of NSUserDefaults. Prepare a plist file in your bundle that contains the default preferences and then use that plist to register the defaults.
NSString *defaultPrefsFile = [[NSBundle mainBundle] pathForResource:#"defaultPrefs" ofType:#"plist"];
NSDictionary *defaultPreferences = [NSDictionary dictionaryWithContentsOfFile:defaultPrefsFile];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultPreferences];
You have to execute this code on every launch of your app. It will add these values to a separate domain in the user defaults hierarchy. Whenever your app's user defaults don't provide a value for a certain key, NSUserDefaults will fall back to this domain and retrieve the value from there.
If you have many default values, let use ola's answer, otherwise this is good for a few params
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults boolForKey:USERDEFAULT_IS_INITIALIZED]) {
[defaults setBool:YES forKey:USERDEFAULT_IS_INITIALIZED];
// Set initial values
...
[defaults synchronize];
}
if ([[[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys] containsObject:#"initialValuesHaveBeenWritten"])
{
[[NSUserDefaults standardUserDefaults] setValue:obj1 forKey:key1];
[[NSUserDefaults standardUserDefaults] setValue:obj2 forKey:key2];
[[NSUserDefaults standardUserDefaults] setValue:obj1 forKey:#"initialValuesHaveBeenWritten"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
NB: Not tested, done from memory
-(void) loadDef
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
_removeAd=[userDefaults boolForKey:SAVE_AD_STATUS];
NSString* strDefSetting=[userDefaults stringForKey:SAVE_STATUS_ADSETTING];
if(strDefSetting==nil
||[strDefSetting isEqualToString:#""]
)
{
strDefSetting=#"0.5";
}
_floatAdmob=strDefSetting.floatValue;//0.5;
}

How to get the nsuserdefault value in other viewcontrollers

I have two viewcontrollers. In my first viewcontroller:
{
NSString *string=textField.text;
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
[data setObject:string forKey:#"strings"];
[data synchronize];
}
How do I get the string value in my other viewcontroller?
Here you can use this in anyway in your application for store value of NSUserDefaults.
// --- Saving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:#"TextToSave" forKey:#"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:#"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:#"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:#"floatKey"];
// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];
Here you can use this in anyway in your application for get value of NSUserDefaults.
// --- Retrieving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:#"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:#"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:#"floatKey"];
you can access NSUserDefaults in any controller (Any class of your application) of your application with the same code you have written in one class.
for getting the string value use the below code
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *myString = [data objectForKey:#"strings"];
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSString *myString = [defaults stringForKey:#"strings"];
THis is the way to retrieve the data. Please note NSUserDefault is not used to pass data between two controllers. There are better methods for that.
Edit : After seeing Shaan Singh's comment
To pass data 2 view controllers you can declare a property in second view controller and access that from the present view controller.
It is already answered brilliantly here.
In the other ViewController,
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *string = [data objectForKey:#"strings"];
This will work because NSUserDefaults are a global key-value store that will persist across classes and applications.

Resources