保存局部变量的值

时间:2014-05-28 18:07:37

标签: ios objective-c persistence

如何在objective-c中保存变量的值,例如BOOL,当我为应用程序返回时,my变量的值是最后设置的值?!例如:

BOOL *firstAccess;

firstAccess = TRUE;

我完成了应用并返回,我希望我的变量再次为TRUE

由于

2 个答案:

答案 0 :(得分:2)

您可以使用NSUserDefaults永久保存数据:

BOOL firstAccess;

/// ...

[[NSUserDefaults standardUserDefaults] setBool:firstAccess forKey:@"FIRSTACCESS"];

要检索值:

firstAccess = [[NSUserDefaults standardUserDefaults] boolForKey:@"FIRSTACCESS"];

有关详细信息,请参阅NSUserDefaults的文档。

答案 1 :(得分:0)

您可以将BOOL值存储在NSUserDefaults

#define MYFirstAccessKey @"firstAccessKey"

+ (void)initialize {
    // Set the default value.  This is returned if nothing has been written for the key.
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{ MYFirstAccessKey : @YES }];
}

- (void)someMethod {
    // Read the value.
    BOOL firstAccess = [[NSUserDefaults standardUserDefaults] boolForKey:MYFirstAccessKey];
    if (firstAccess) {
        // ... do stuff ...
    }

    // ... later ...

    // Set value.
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:MYFirstAccessKey];
    [[NSUserDefaults standardUserDefaults] synchronize];  // Write to disk now.

}