Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving an int from NSUserDefaults

How do I retrieve an int from NSUserDefaults?

I have the following code

NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
NSArray *prefs = [def arrayForKey:@"addedFavs"];    
favList = [[NSMutableArray alloc] initWithArray:prefs];

If I try this

NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
int tempInt = [def objectForKey:@"addedFavs"];  

will I not need to do type casting?

like image 776
some_id Avatar asked Jul 18 '10 10:07

some_id


People also ask

How do you save NSUserDefaults in Objective C?

Saving to NSUserDefaults : Basically, all you have to do is load NSUserDefaults, and then tell it to save a value to a specific key. Here is a simple example of writing an integer to NSUserDefaults: NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

How does NSUserDefaults work?

NSUserDefaults caches the information to avoid having to open the user's defaults database each time you need a default value. When you set a default value, it's changed synchronously within your process, and asynchronously to persistent storage and other processes.

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.

What is NSUserDefaults in swift?

A property list, or NSUserDefaults can store any type of object that can be converted to an NSData object. It would require any custom class to implement that capability, but if it does, that can be stored as an NSData. These are the only types that can be stored directly.


2 Answers

You can use -[NSUserDefaults setInteger:forKey:] to store the value and -[NSUserDefaults integerForKey] to retrieve it.

like image 115
shosti Avatar answered Oct 07 '22 18:10

shosti


Have you looked in at NSUserDefaults in the documentation? There is a integerForKey: method that will retrieve an integer for a given key.

NSInteger tempInt = [[NSUserDefaults standardUserDefaults] integerForKey:@"aKey"];
like image 39
Tom Irving Avatar answered Oct 07 '22 18:10

Tom Irving