Saving NSNumber in NSUserDefaults
Asked Answered
S

3

6

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.

Schizothymia answered 12/4, 2014 at 22:16 Comment(0)
M
8

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.

Marchpast answered 13/4, 2014 at 0:1 Comment(1)
did it help you @Schizothymia ?Marchpast
D
5

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).

Douzepers answered 12/4, 2014 at 22:26 Comment(1)
Just to clarify, setInteger:forKey: is a conveniences method that takes you NSInteger and converts it into a NSNumber for you. Similarly integerForKey: is a converts your stored NSNumber into an NSInteger.Narvaez
P
0

You need to do the 'opposite' to get it back out

 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
 NSInteger currentIndex = [defaults integerForKey:@"currentIndex"];
Pidgin answered 12/4, 2014 at 22:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.