Using currentIndex as NSNumber and saving NSNumber in NSUserDefaults.
Using currentIndex to store bookmarked page in NSUserDefaults
And this is how I am saving currentIndex in NSUserdefaults:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:currentIndex forKey:@"currentIndex"];
[defaults synchronize];
If this is the right way of saving currentIndex in NSUserdefaults then how can i retrieve saved currentIndex in NSUserdefaults.
Thanks for help.
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];
You can save your mutable array like this: [[NSUserDefaults standardUserDefaults] setObject:yourArray forKey:@"YourKey"]; [[NSUserDefaults standardUserDefaults] synchronize]; Later you get the mutable array back from user defaults. It is important that you get the mutable copy if you want to edit the array later.
Storing Default Objects The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Boolean values, and URLs.
The user's defaults database is stored on disk as a property list or plist. A property list or plist is an XML file. At runtime, the UserDefaults class keeps the contents of the property list in memory to improve performance. Changes are made synchronously within the process of your application.
The title says that you want to store a NSNumber, you should do that in this way:
obj-c
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:nsnumberObject forKey:@"nsNumberStored"];
swift
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(nsnumberObject, forKey:"nsNumberStored")
And then to fetch the NSNumber do this:
obj-c
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSNumber *nsNumberFetched = [defaults objectForKey:@"nsNumberStored"];
swift
let defaults = NSUserDefaults.standardUserDefaults()
defaults.objectForKey("nsNumberStored")
You can read the official documentation here Class reference
Let me know if it helps you.
First of all, setInteger: forKey:
is used to store an int
, not a NSNumber
. If you want to store a NSNumber
, user setObject: forKey:
.
In order to retrieve your stored data, use objectForKey:
(or integerForKey:
instead if you would rather use int
's).
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