Save data to a file for next iPhone app launch
Many times you need to save some user preferences or session data that will load automatically upon the next launch of your iPhone app. Unfortunately this is quite a bit harder than it looks. Here are simple steps on how to save a string from your application. Just change the variable type to save more information!
Let’s assume you want to save the user’s account number.
Add the following to AppDelegate.h like you would normally create a mutable string:
NSMutableString *accountName;
@property (nonatomic, retain) NSMutableString *accountName;
Add the following to the top of AppDelegate.m. I put this between my import and implementation statements.
NSString *kAccountName = @"AccountName";
Add the following to applicationDidFinishLoading in AppDelegate.m:
NSMutableString *tempMutableAccountName = [[[NSUserDefaults standardUserDefaults] objectForKey:kAccountName] mutableCopy];
self.accountName = tempMutableAccountName;
[tempMutableAccountName release];
Add the following to applicationWillTerminate in AppDelegate.m:
[[NSUserDefaults standardUserDefaults] setObject:accountName forKey:kAccountName];
In the application itself, you will need to add the following code where you want to set this value to prepare for saving on application termination:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.accountNumber = x;
To grab this value from the saved variable, add these lines:
MobilePOSAppDelegate *appDelegate = (MobilePOSAppDelegate *)[[UIApplication sharedApplication] delegate];
x = appDelegate.accountNumber;
Now you can save data from your app so it can be loaded automatically next time!
Hey, just so you know, I’ve tried this sample code and it just plain doesn’t work at all. It doesn’t save the values, I mean, it writes them but it doesn’t save them at all. Is there additional setup required that you hadn’t mentioned?
Sorry was away when you commented and just saw it again now. I really have all the code included that is necessary. If you solved this problem, I’d be interested toa you did to make it work.