Home / iPad

Adding a Constants.h file

To save and read settings in your app, you can use a built-in, easy-to-use class that lets you read and set user preference settings from your app - NSUserDefaults. The class is also used by the Settings app that comes with your iPad (which Apple has graciously consented to let us peons use).

You use NSUserDefaults to read and store preference data to a default database, using a key value - just as you would access keyed data from an NSDictionary. The particular keys you will use are kWordsOfWisdom for the falling words replacement text, kSpeed for the animation speed, and kMaxSpeed for the maximum speed possible.

To use keys like kWordsOfWisdom, kSpeed, or kMaxSpeed, you need to first define them in a Constants.h file. To implement the Constants.h file in your project, do the following:

  1. Select the project name (DeepThoughts) in the Groups & Files list and then choose File → New File from the Xcode main menu.
  2. In the New File dialog that appears, choose Other from the listing on the left (under the Mac OS x heading) and then choose Empty File in the main pane.
  3. In the new dialog that appears, name the file Constants.h and then click Finish.
    Don't make any other changes - just the name. The Add to Project pop-up menu should already be set to the name of the project - DeepThoughts (if not, choose the name of the project from the menu).
    The new empty Constants.h file is saved in your project at the bottom of the DeepThoughts group (under Products), but you can drag it up to the top of the group, above Classes. Typically do this so that the Constants.h file is easy to find and change.

With a new home for your constants all set up and waiting, all you have to do is add the constants you need:

#define kWordsOfWisdom 	@"wordsOfWisdomPreference"
#define kSpeed 			@"speedPreference"
#define kMaxSpeed 			      20.0

Having a Constants.h file in hand is great, but you have to let DeepThoughtsViewController.m know that you plan to use it, as I show in the next section.

Note: It may seem like you are starting at the end and working backwards, but it makes sense to show the code in DeepThoughts that uses these settings first and then show in next tutorial how you can enable the user to change and save these settings.

To put the settings to use in the app's view, you have to link it up with the view's controller - in this case, DeepThoughtsViewController. The best place to do that is viewDidLoad, which is invoked right after the view has been loaded from the nib file. viewDidLoad is found in the DeepThoughts ViewController.m file, so that's where you'd go to insert your code to use the settings to control the animated view. The next section shows you how that's done.

[Previous] [Contents] [Next]