How to save variables after application shut down?

帅比萌擦擦* 提交于 2019-11-30 15:36:08

You should store and load data from NSUserDefaults:

http://developer.apple.com/library/IOS/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// to store
[defaults setObject:[NSNumber numberWithInt:12345] forKey:@"myKey"];
[defaults synchronize];

// to load
NSNumber *aNumber = [defaults objectForKey:@"myKey"];
NSInteger anInt = [aNumber intValue];

Check out the NSUserDefaults documentation. You can set arbitrary key-value pairs there which (as long as you call the shared user defaults object’s -synchronize at some point before your app terminates) will persist between launches.

You can save them in the NSUserDefaults. This is mainly used for preferences.

[[NSUserDefaults standardUserDefaults] setObject:someInteger forKey:@"someIntegerKey"];
[[NSUserDefaults standardUserDefaults] synchronize];

You can also save them to a Property List file if you have more data you'd like to store.

NSDictionary *someDictionary = [NSDictionary dictionaryWithObjectsAndKeys:someInt1, @"someIntKey1", someInt2, @"someIntKey2", nil];

[someDictionary writeToFile:somePath error:&error];

To save upon exiting the app place any code in

- (void)applicationWillTerminate:(UIApplication *)application

Look into using NSUserDefaults. This works like a dictionary that you can add key/value pairs to. You save the variables in your app delegate's applicationWillTerminate and applicationDidEnterBackground methods. You load the variables again in applicationDidFinishLoading.

The easiest way is to use NSUserDefaults. Your app delegate will get an -applicationWillTerminate: message when the app is about to shut down, and you can write your data to NSUserDefaults (or write it into your own file if the amount of data is large). Then, when your app starts up again, your app delegate will get an -applicationDidFinishLaunching, and you can read your data back again.

Serialize them and store them on memory. You have to do this before shut down and load when app is reopened

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!