如何在我的应用加载之前从NSUserDefaults中检索值?

时间:2012-08-20 02:00:40

标签: ios cocoa-touch ios5 nsuserdefaults

我有一个ViewController,在点击按钮时,标签会更新。我想要的是,每次应用程序打开时,都应保留其旧值。我能够在NSUserDefault中写入每个值,但在应用加载之前无法获得如何在标签上写入值。
示例:
在第一次运行中,标签的值为5。 在第二次运行中,标签应包含相同的值5,如果我做了任何更改,那么更改应该在第三次运行中。
感谢名单...

2 个答案:

答案 0 :(得分:2)

在你的AppDelegate中,第一个方法在启动App后被调用,

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    return YES;
}

以及其他情况,例如从应用程序使用的非活动状态到活动状态,

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

我建议阅读,Apple's iOS application lifecycle documentation

答案 1 :(得分:1)

以下是从NSUserDefaults检索存储值并在ViewController加载时设置标签值的方法:

- (void)viewDidLoad
{
    [super viewDidLoad];    
    self.myLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"mySavedValue"];
}

我假设你的按钮已经连接到这样的动作,它会在点击时将值保存到standardUserDefaults:

- (IBAction)buttonPressed:(id)sender
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.myLabel.text forKey:@"mySavedValue"];
    [defaults synchronize];
}