User Tools

Site Tools


ios-labs-s14:intermediate-defaults

NSUserDefaults

A dictionary containing objects in binary form that is saved to the device. Useful for storing data and objects.

Example saving data:

NSData *save = [NSKeyedArchiver archivedDataWithRootObject:ARRAY];
[[NSUserDefaults standardUserDefaults] setObject:save forKey:@"KEY"];
[[NSUserDefaults standardUserDefaults] synchronize];

Note that the synchronize call is not normally needed, but saves are asynchronous and may not appear right away without it.

NSKeyedArchiver- takes an object, recursively calls coding methods rendering the objects into dictionaries (more or less). Any objects created by the developer must implement these coding methods (google NSCoding protocol), any stock iOS objects (dictionaries, arrays, strings, etc) can be archived without changes.

Example loading data:

NSData *save = [[NSUserDefaults standardUserDefaults] objectForKey:@"KEY"];
ARRAY = [NSKeyedUnarchiver unarchiveObjectWithData:save];

Binary data is first retrieved from the key @“KEY” and then unarchived back into its constituent objects. Note that the resulting data type may not be an array as shown; it is the developer's responsibility to ensure the objects being unarchived are the same type as the one that was archived.

ios-labs-s14/intermediate-defaults.txt · Last modified: 2014/02/23 22:06 by mbarboi