// Grab the default archive
NSUserDefaults *archive = [NSUserDefaults standardUserDefaults];
// Create a magic key for the value you're about to load or save
NSString *key = [[NSString alloc] initWithFormat:@"myData"];
// To save
[archive setFloat:vector->x forKey:vectorKeyX];
// To load
vector->x = [archive floatForKey:vectorKeyX];
// Don't forget to release the key
[key release];
// Creates the unique key for our object
+(NSString*)getSerializeKey:(uint)index key:(NSString*)key
{
if( key == nil )
{
return [[NSString alloc] initWithFormat:@"Obj%i", index];
}
else
{
return [[NSString alloc] initWithFormat:@"%@Obj%i", key, index];
}
}
// Creates our key and passes it into the serializeInternals function for saving the internal data
-(void)serialize:(NSUserDefaults*)archive saving:(BOOL)saving key:(NSString*)key index:(uint)index
{
NSString *objectKey = [ObjectBase getSerializeKey:index key:(NSString*)key];
// The internal index will aid the creation of unique keys for our internal data
uint internalIndex = 0;
[self serializeInternals:archive saving:saving key:key index:&internalIndex];
[objectKey release];
}
// Overridden by child classes to save more data
-(void)serializeInternals:(NSUserDefaults*)archive saving:(BOOL)saving key:(NSString*)key index:(uint*)index
{
// Save our object position by default
[self serializeVector:&position archive:archive saving:saving key:key index:index];
}
// Save/load our scenes with a unique scene key
+(void)serializeScene:(SceneBase*)scene archive:(NSUserDefaults*)archive saving:(BOOL)saving key:(NSString*)key
{
NSString *sceneKey = [[NSString alloc] initWithFormat:@"%@Scene", key];
if( saving )
{
[archive setInteger:scene ? scene->index : -1 forKey:sceneKey];
}
else
{
NSInteger sceneIndex = [archive integerForKey:sceneKey];
[gEngine addScene:sceneIndex];
}
[sceneKey release];
}
// The keys for the objects internal vectors are concatenated by the object key and the internal index key
-(void)serializeVector:(Vector3*)vector archive:(NSUserDefaults*)archive saving:(BOOL)saving key:(NSString*)key index:(uint*)index
{
NSString *vectorKeyX = [[NSString alloc] initWithFormat:@"%@Vector%iX", key, *index];
NSString *vectorKeyY = [[NSString alloc] initWithFormat:@"%@Vector%iY", key, *index];
NSString *vectorKeyZ = [[NSString alloc] initWithFormat:@"%@Vector%iZ", key, *index];
if( saving )
{
[archive setFloat:vector->x forKey:vectorKeyX];
[archive setFloat:vector->y forKey:vectorKeyY];
[archive setFloat:vector->z forKey:vectorKeyZ];
}
else
{
vector->x = [archive floatForKey:vectorKeyX];
vector->y = [archive floatForKey:vectorKeyY];
vector->z = [archive floatForKey:vectorKeyZ];
}
[vectorKeyX release];
[vectorKeyY release];
[vectorKeyZ release];
(*index)++;
}