简体   繁体   中英

How to Persist Application State in cocoa

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

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 .

- (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM