iOS Tips: NSUserDefaults

  1. How to process default value?

  1. Rephrase all user defaults keys so that NO or 0 is the correct default value. In our example, this would mean renaming "ShowTutorial" to "HideTutorial". This may be a workable solution for boolean values, but is extremely impractical or impossible for numbers and more complex values.
  2. Always use -[NSUserDefaults objectForKey:] instead of the primitive accessor methods:

    NSNumber *showTutorialOnLaunch = [[NSUserDefaults standardUserDefaults] objectForKey:@”ShowTutorial”];

    if (showTutorialOnLaunch == nil) { // No value found

          showTutorialOnLaunch = @YES;



    objectForKey: returns nil when a value is not present, which can be distinguished from a valid object that represents NO or 0. This works but makes the code less readable and more complex than it needs to be.

  3. Write custom code that stores the default values for all preferences in the user defaults on the first launch of your app (requiring another flag that tells your app whether it is being launched for the first time or not). This is essentially what we will do, but in a more elegant way.


Apple Doc



About liyao13

Yao Li is a web and iOS developer, blogger and he has a passion for technology and business. In his blogs, he shares code snippets, tutorials, resources and notes to help people develop their skills. Donate $5 to him for a coffee with PayPal at About Me page and read more professional and interesting technical blog articles. Follow him @Yaoli0615 at Twitter to get latest tech updates.
This entry was posted in iOS, Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s