开发者

Saving application data state on exit

I have an NSMutableArray with 24 strings.

开发者_如何学Go

I need to save this data if a user gets a call or quits the application.

I have been looking into many examples but for some reason can’t seem to determine the best way to save the data.

The 24 strings correspond to 24 buttons and their state. When a button is clicked, it displays the corresponding Array info for that buttons tag (0 – 23). What I would need to retain is if 10 buttons where clicked and their data shown, how/what would be the best way of retaining this data so it can be reloaded when the app starts?

I am thinking I would need to store:

Button Tag, Buttons corresponding Array value,

Button state (whether it has clicked and value is show or not)

I would store this data on exit of the application and then when app is started again, I would determine if this stored data exists, if so populate the array and examine the button states to determine if it had already been shown and if so, set it accordingly. Then when this file was loaded, I would delete the stored data (.DAT file if stored this way). This way if a user quits gracefully, on next start up, it would start a new game.

I have looked at several examples where they store data into a .DAT file but am having problem implementing this….and wondering if this is even the best way.

Any help or thoughts on this is greatly appreciated.

Geo…


you should be able to store 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];


You could save the data to a plist in the Documents directory. If the data is there, load it up, and if not, it would suggest a clean run.

To load the 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 the data:

[buttonState writeToFile:filePath atomically: YES]; 


I save my data by using NSKeyedArchiver/NSKeyedUnarchiver, since your NSMutableArray already supports the NSCoding protocol, you can just use

yourArray = [NSKeyedUnarchiver unarchiveObjectWithFile:file];

[NSKeyedArchiver archiveRootObject:yourArray toFile:file];

Edit:

I suppose NSArray's own methods work also

[NSArray writeToFile:]
[NSArray initWithContentsOfFile:]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜