Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUserDefaults Contains Value Or Not?

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

like image 266
Aswathy Bose Avatar asked Feb 09 '12 06:02

Aswathy Bose


People also ask

What is NSUserDefaults?

The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an app to customize its behavior to match a user's preferences. For example, you can allow users to specify their preferred units of measurement or media playback speed.

How do you check if NSUserDefaults is empty in Objective C?

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.

Where are NSUserDefaults stored?

All the contents saved by NSUserDefaults is saved inside a plist file that can be found under Library -> Preferences -> $AppBundleId.

Is NSUserDefaults thread safe?

The NSUserDefaults class is thread-safe.


2 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
}
like image 154
Krishnabhadra Avatar answered Sep 29 '22 13:09

Krishnabhadra


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"];
like image 44
Parag Bafna Avatar answered Sep 29 '22 13:09

Parag Bafna