The simplest way to save user states in iOS is through NSUserDefaults.
Here is an example which keeps track of all changed made to your singleton:
@interface MySingleton : NSObject
{
}
+ (MySingleton *)sharedSingleton;
@property (copy) NSString *userName;//the variable to track
@end
@implementation MySingleton
@synthesize userName;
+ (MySingleton *)sharedSingleton
{
static MySingleton *sharedSingleton;
@synchronized(self)
{
if (!sharedSingleton)
sharedSingleton = [[MySingleton alloc] init];
return sharedSingleton;
}
}
- (void)setUserName:(NSString*)userName
{
//update the variable
self.userName = userName;
//saves the new value to NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:userName forKey:@"userName"];
//forces instantaneous synchronization, not needed, would be updated after a periodic interval anyways
[[NSUserDefaults standardUserDefaults] synchronize];
}
@end
Optionally you can implement the NSCoding
protocol and save the whole class to NSUserDefaults
, take a look at this question.