Saving application data state on exit

I have an NSMutableArray with 24 lines.

I need to save this data if the user receives a call or leaves the application.

I looked at a lot of examples, but for some reason can not seem to determine the best way to save data.

24 lines correspond to 24 buttons and their status. When a button is pressed, the corresponding array information for the button tag is displayed (0 - 23). What I would need to save is 10 keystrokes of the buttons and their data, how / what would be the best way to save this data so that it can be reloaded when the application starts?

I think I will need to store:

Button label, Buttons corresponding to the value of the array,
Button state (regardless of whether it was pressed and the value is displayed or not)

I would save this data when I exit the application, and then when the application started again, I would determine if this saved data exists, if so, fill the array and examine the state of the buttons to determine if it has already been shown, and if so install it accordingly. Then, when this file was downloaded, I would delete the saved data (.DAT file if it was saved this way). Thus, if the user exits gracefully, the next time he starts, he will start a new game.

I looked at a few examples in which they store data in a .DAT file, but I have a problem with this ... and I wonder if this is even the best way.

Any help or thoughts on this subject are welcome.

Geo ...

+4
source share
3 answers

You can save the data in plist in the Documents directory. If there is data, download it, and if not, it will offer a clean run.

To load data:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documents = [paths objectAtIndex:0]; NSString *filePath = [documents stringByAppendingPathComponent:@"buttonState.plist"]; NSMutableDictionary *buttonState = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath]; 

To save data:

 [buttonState writeToFile:filePath atomically: YES]; 
+2
source

you can save it in NSUserDefaults

 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:buttonState forKey:@"buttonState"]; [defaults synchronize]; // Then to get the state back NSMutableArray* buttonState = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"buttonState"] mutableCopy]; 
+5
source

I save my data with NSKeyedArchiver / NSKeyedUnarchiver , since your NSMutableArray already supports NSCoding protocol, you can simply use

 yourArray = [NSKeyedUnarchiver unarchiveObjectWithFile:file]; [NSKeyedArchiver archiveRootObject:yourArray toFile:file]; 

Edit:

I believe that NSArray own methods work

 [NSArray writeToFile:] [NSArray initWithContentsOfFile:] 
+1
source

Source: https://habr.com/ru/post/1300210/


All Articles