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

- 4,279
- 4
- 32
- 44
3 Answers
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
}

- 1,477
- 1
- 16
- 35

- 34,169
- 30
- 118
- 167
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"];

- 22,812
- 8
- 71
- 144
-
You should compare to nil, not NULL, as @Krishnabhadra states. – Philippe Sabourin Feb 09 '12 at 06:29
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.

- 24,039
- 5
- 57
- 72