Adding Defaults to GraphPaper

In this section, we’ll modify the GraphPaper application to work with the defaults database. We will do this by making changes to both the Controller and the ColorGraphView classes.

Cocoa applications use a single instance of the Foundation class NSUserDefaults for managing the defaults database. Apple’s documentation notes that the NSUserDefaults class is not thread-safe, so you should use it only from your application’s main thread.

To use the NSUserDefaults class, you must first decide what default values your application will need to store. Each of these values should be given a name that will be its key in the defaults database. For each value, you must also decide upon a representation — that is, how the representation will be stored. Table 21-3 shows the defaults that we will use for GraphPaper.

Table 21-3. Defaults for the GraphPaper application

Default name

#define

Our default

AxesColor

GP_AxesColor

[NSColor red]

LabelColor

GP_LabelColor

[NSColor blue]

GraphColor

GP_GraphColor

[NSColor black]

xstep

GP_xstep

0.1

xmin

GP_xmin

-10.0

xmax

GP_xmax

10.0

ymin

GP_ymin

-5.0

ymax

GP_ymax

5.0

formula

GP_Formula

cos(x)

GraphPaper window frame

Not needed

NSMakeRect(0,0,500,500)

Once you have decided on the default values that your application will be using, you need to write the code that will install these into the default registration table. This table will provide the default ...

Get Building Cocoa Applications: A Step by Step Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.