2010-02-21 91 views
4

我有一种感觉,有一种简单的方法来做到这一点。我有一个介于1和100之间的数字,它存储在一个名为firstValue的变量中。这个变量然后被放入一个UILabel。当用户退出我的应用程序时,我希望保存这个firstValue,以便在用户加载该应用程序时,可以将此号码重新插入到UILabel(firstValueLabel.text)中。保存并加载单个值,iPhone

非常感谢,

斯图尔特

回答

14

您可以使用NSUserDefaults进行此操作。

要保存它:

NSInteger myValue = ...; // This is your number 
NSString *key = ... ; // This is a string to identify your number 
[[NSUserDefaults standardUserDefaults] setInteger:myValue forKey:key]; 

来阅读:

NSInteger myValue = [[NSUserDefaults standardUserDefaults] integerForKey:key]; 

如果没有以前的值已经保存,返回值为0

添加到您的applicationWillTerminate :

[[NSUserDefaults standardUserDefaults] synchronize]; 
+1

最好打电话在你改变了值之后的'synchronize'方法。以防万一您的应用程序因其他原因崩溃或停止。 – 2010-02-22 02:16:26

3

你可以使用NSUserDefaults的存储一些变量为您的应用程序的结束后对它们进行检索。 对于为例:

// Set the name of the view 
[[NSUserDefaults standardUserDefaults] setInteger:10 forKey:@"firstValue"]; 

为了获取用户的最后一个动作:

// Retrieve the last view name 
Integer firstValue = [[NSUserDefaults standardUserDefaults] integerForKey:@"firstValue"]; 

但您可以添加其他的不是整数。 (请参见NSUserDefaults Class Reference