# teaching machines

## CS 491 Lecture 13 – Persisting with Preferences

October 15, 2013 by . Filed under cs491 mobile, fall 2013, lectures.

### Agenda

• what ?s
• the need for persistence
• the need for lightweight persistence
• persisting in TicTacToe

### Exercise

Apps are made to be interrupted. Let’s get our hands dirty by implementing a game of TicTacToe, preserving the game state on interruption, and restoring the game from the persisted state on resume. Write a quick and dirty TicTacToe game on the platform of your choice.

Layout is not our focus today, so please don’t spend time perfecting your user interface. I recommend slapping on 9 buttons in a 3×3 grid in a slipshod manner.

#### iOS Tips

• It’s easy enough to make IBOutlet properties for each of your buttons with:
@property (nonatomic, weak, readonly) IBOutlet UIButton *button0;

However, discrete, named properties are difficult to loop through. If we could make an array of IBOutlets, that’d be swell. Apparently Xcode 5 makes this easy, but we’re using Xcode 4. Check out this post for a possible solution.

• One way to know an app is pausing is by overriding viewWillDisappear.
• Preferences are key-value pairs. Values can be of several types. Writing preferences is done the set methods:
[[NSUserDefaults standardUserDefaults] setObject:self.state forKey:@"state"];
[[NSUserDefaults standardUserDefaults] setInteger:self.current forKey:@"current"];

Reading is done with getter methods.

#### Android Tips

• There are various ways to make a grid of views. The most primitive and perhaps fastest is a vertical LinearLayout of three horizontal LinearLayouts.
• Preferences come in two varieties: named and default. Default preferences are best suited for app-wide settings. You can get a reference to the app-wide preferences in this way:
private SharedPreferences prefs;
... {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
}

where this refers to the Activity/context.  Named preferences let you group preferences together in smaller, more tailored bundles or make them readable by other apps.

• Altering preferences requires a database-like transaction. Create an Editor, insert or overwrite your key-value pairs, and then commit your changes:
Editor editor = prefs.edit();
editor.putString("mykey", myvalue);
editor.apply();

A great place to commit is onPause, which is called before your app is removed from the foreground.

### Haiku

Pity the just-names