Save and restore preferences Many applications have some data that must be saved when it quits and restored when it is started again, for example, a list of stocks to be followed in the market. One could write the data to a file and read it in again, but iOS provides a mechanism for just this purpose. It is defined in a class called NSUserDefaults. NSUserDefaults sets and gets values by key just like NSDictionary. Here is an example, static NSString *MatrixSignatureKey = @"MatrixSignatureKey"; - (void) restorePreferences
{
// Restore matrix so the earth looks as it did when we closed.
NSData *asData= [[NSUserDefaults standardUserDefaults] dataForKey:MatrixSignatureKey];
GLfloat currentMatrix[16];
if (asData != nil)
{
//move bytes to currentMatrix
[asData getBytes:currentMatrix length:sizeof(currentMatrix)];
[glView loadModelViewMatrix:currentMatrix];
}
asData= [[NSUserDefaults standardUserDefaults] dataForKey:kilometersSignatureKey];
if (asData != nil)
{
//move bytes
bool qk;
[asData getBytes:&qk length:sizeof(bool)];
setKilometers(qk);
}
}
restorePreferences would normally be called in the appDelegate method didFinishLaunchingWithOptions. savePreferences should be called in the delegate method applicationDidEnterBackground. In older systems without multitasking it should be called in applicationWillTerminate. Calling it in both places is safe and wise. You could also choose to call it immediately after changing any of the preferences. NSData is a special type designed to hold a certain number of bytes representing any kind of data. Here it is used to hold 16 floating point numbers for the matrix and one byte for a boolean value. NSData inherits from NSObject so it is a proper object and can be used in NSDictionarys, NSArrays and so forth. If the data you want to save is already a proper object you don't need to wrap it in NSData.
|