~If you would like to request a tutorial, email Collateral at collateraldamag3@gmail.com~

Share This!

iPhone Tutorial ~ NSUserDefaults and Settings.bundle - Part I


Alright, This is a tutorial on the NSUserDefaults feature and how to use them in conjunction with Settings.bundle.

First off, What is NSUserDefaults? If you want the "Apple Definition" you can find it HERE. But basically, NSUserDefaults is a way to store data for a another point in time. You can use NSUserDefaults to save a character's level, or what items he/she's carrying. Or You can use it to remember a username and password or whether the user prefers a light or dark GUI. Basically, it saves stuff. 
So how do I use NSUserDefaults? Well, Apple has made it VERY easy actually. There are two ways to access data in NSUserDefaults, saving data and loading data. We'll start with saving.

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger: 0 forKey: @"whatever"];//Save
[prefs synchronize];

 That ^^ is a very simple example of saving data to NSUserDefaults. I'm starting off by labeling [NSUserDefaults standardUserDefaults] as just simply "prefs", mostly because prefs is about 20x easier to write.  I am then saving "0" as an integer to the key "whatever". Now, you may be asking, what is a key? A key is basically a save slot. whenever you have an option you have a slot. For example, if you have a game where you have to save the character's inventory, you will probably store an array of the character's objects into a key named "inventory". Basically a key is a spot in the NSUserDefaults where certain info is stored.  And [prefs synchronize] just writes it to the disk.

Here are the different syntaxes you can use when saving to NSUserDefaults (of course all linked to their reference :p):

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *strUserName = [prefs stringForKey:@"userName"];

Here I am loading a String from the key "userName" and storing it into a NSString titled "strUserName". Easy Peasy. Here are the syntax's and references for what you can use while loading data. Be careful it IS different from the first list.

No comments:

Post a Comment

This entry is filed under .

You can also follow any responses to all entry through the RSS Comments feed.