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?
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];
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.
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.
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.
You can use -[NSUserDefaults setInteger:forKey:]
to store the value and -[NSUserDefaults integerForKey]
to retrieve it.
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With