-1

可能重复:
应用程序关闭后如何保存变量?

我正在使用objective-c在单视图应用程序中制作Iphone应用程序,我希望能够保持变量记录分数以控制可解锁字符、高分等。

问题是每次我关闭并重新打开应用程序时,变量都会重置。

有谁知道如何制作一个在重新打开时永远不会重置的变量?

4

2 回答 2

4

On iOS you store variables between runs by using NSUserDefaults. See an example code below:

#define HSMEMORY @"hsMemory"  // used to prevent errors in writing it repeatedly

    // Store initial default values. Do this at the beginning of the App like in AppDelegate before the values are used and accessed.
    // This will set the initial value when the App is first run and nothing has been stored in previous runs.
        NSNumber *defaultMemory = [NSNumber numberWithDouble:0.0];
        NSDictionary *appDefaults = [NSDictionary
                                         dictionaryWithObjectsAndKeys:
                                         defaultMemory, HSMEMORY, nil];
        [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];

To access the variable use:

NSNumber *memory = [[NSUserDefaults standardUserDefaults] objectForKey:HSMEMORY];

To reset the variable use:

[[NSUserDefaults standardUserDefaults] setObject:memory forKey:HSMEMORY];
于 2012-09-15T20:54:57.117 回答
0

我相信当您说“变量”时,您的意思是 NSString,所以在这种情况下,您可以使用 NSUserDefaults 来实现这一点。但请记住,NSUserDefaults,顾名思义,应该存储少量数据,所以不要继续使用它太多了。

保存一个 NSString:

//Initialize NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//Store the desired value
[defaults setObject:@"TEXT TO SAVE OR NSSTRING" forKey:@"CHOOSE A KEY-NAME"];
//To retrieve the text when the app launch
NSString *value_retrieved = [defaults objectForKey@"YOUR KEY-NAME"];

保存 BOOL 键

//Initialize NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//Save the Boolean
[defaults setBool:YES OR NO forKey:@"CHOOSE A KEY-NAME"];
//Retrieve the Boolean
[defaults boolForKey:@"YOUR KEY-NAME"];
于 2012-09-16T02:46:20.297 回答