Coding, How-To

iOS: Save/Retrieve Data Using NSUserDefaults

If you need to access the value of some variable in your app later on, be it in the same class or not, you might like to save it first using NSUserDefaults.

Here’s an example with an NSString variable:

NSString *yourString = @"yourValue";
[[NSUserDefaults standardUserDefaults] setObject:yourString forKey:@"stringKey"];
[[NSUserDefaults standardUserDefaults] synchronize];

If you have an NSInteger type variable instead, change your second line to:

[[NSUserDefaults standardUserDefaults] setInteger:yourInteger forKey:@"integerKey"];

You may implement similarly for float or double values using setFloat or setDouble respectively.

Make sure you remember to synchronize, otherwise this may not always work properly.

To retrieve the value later on, use the same key:

NSString *thatSameString = [[NSUserDefaults standardUserDefaults] stringForKey:@"stringKey"];

In this case, it is preferable that you store the key as a constant somewhere else in your app. There is a guide here.

Leave a Reply

Your email address will not be published. Required fields are marked *