How to Persist Application State in cocoa

1.8k Views Asked by At

I need to store the state of application at application termination time, so that when user re-run app, App run from the state in which it was closed last time. It is some kind of restoring app but restore methods called when app close unexpectedly. But i need to restore app each time when it close unexpectedly of user close it manually. I just need to store the App UI not the data of application. Any idea would be helpful for me. Thanks

2

There are 2 best solutions below

2
On

You can persist the state in any of the available methods like:

i. NSUserDefaults

Example:

//saving
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:YES forKey:@"testBool"];
//retrieving
[defaults boolForKey:@"testBool"];

ii. Serializing the state object.

iii. Saving as a plist file

Example:

NSMutableDictionary *stateDictionary = [NSMutableDictionary dictionary];
//set state
...

//saving
[stateDictionary writeToFile:<filePath> atomically:YES];

//retrieve
stateDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:<filePath>]

iv. Using sqlite or Core-Data

(Most probably not needed unless the state of your app is in some kind of a object relational model)

UPDATE:
For preserving the UI state of windows, Check this link and under the heading USER INTERFACE PRESERVATION.

3
On
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
    //saveData
    return NSTerminateNow;
}

If you want to save NSWindow position , you can use [window saveFrameUsingName:@"myWindow"];
and use
[window setFrameAutosaveName:@"myWindow"]; @ the app launch.