Updating a Preference

An obvious example of simple preference updating is a game that searches for a high score preference each time a round is completed. If there is no high score preference, the application would just write the current score as the high score. If a high score preference exists, the application would compare the old score with the new score and update the preference if the new score is higher. Listing 1-3 demonstrates this process.

Listing 1-3 Updating a preference
CFStringRef highScoreKey = CFSTR("High Score"); int highScore; Boolean valueValid; // Look for the preference. highScore = CFPreferencesGetAppIntegerValue(highScoreKey, kCFPreferencesCurrentApplication, &valueValid); // If the preference exists, update it. If not, create it. if (valueValid) { printf("The old high score was %d."), highScore); } else { // No previous value. printf("There is no old high score.")); highScore = 0; } highScore += 5; // Create the CFNumber to pass to the preference API. tempScore = CFNumberCreate(NULL, kCFNumberIntType, &highScore); // Set the preference value, or update it if it already exists. CFPreferencesSetAppValue(highScoreKey, tempScore, kCFPreferencesCurrentApplication); // Release the CFNumber. CFRelease(tempScore);

The technique shown in Listing 1-3 generalizes to the typical preference operations. The technique also works for the more complex situation of multiple preferences. In this scenario, an application tries to locate a set of preferences for display to the user in a graphical preference dialog. If no preferences exist, default values are used to initalize the preference dialog for display to the user. If existing preference values are found, they are used instead of the defaults. As the user makes changes you would set the changed preference values. When the dialog is dismissed, you can write the changed values, or the entire set, to permanent storage.


© 2000 Apple Computer, Inc. (Last Updated 14 July 2000)