如何保存iPhone应用程序的用户首选项?

时间:2010-08-25 13:11:23

标签: ios objective-c iphone

问题标题几乎让它消失了 - 我希望我的应用程序记住一些事情。它是某种计算器,因此它应该保存最后使用的值和一些用户可选择的设置。

基本上我想保存一些浮动和BOOL,并在下次加载应用程序时再次加载它们。

最好和最简单的方法是什么?

谢谢!

5 个答案:

答案 0 :(得分:128)

最简单的方法之一就是将其保存在NSUserDefaults

环境:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

[userDefaults setObject:value 
                 forKey:key];
// – setBool:forKey:
// – setFloat:forKey:  
// in your case 
[userDefaults synchronize];

获得:

[[NSUserDefaults standardUserDefaults] objectForKey:key];

– boolForKey:

– floatForKey:在您的情况下。

答案 1 :(得分:6)

除了非常好的NSUserDefaults方法之外,还有另一种简单的方法可以将NSArray,NSDictionary或NSData中的数据存储在文件中。您也可以使用这些方法:

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

分别(对于NSDictionary):

+ (id)dictionaryWithContentsOfFile:(NSString *)path

你只需要提供一个有效的路径到一个位置。根据iOS应用程序编程指南,/ Library / Caches目录是存储应用程序启动之间需要保留的数据的最佳位置。 (见here

为了在您的文档中存储/加载名为“managers”的字段中的字典,您可以使用以下方法:

-(void) loadDictionary {
    //get the documents directory:
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDirectory = [paths objectAtIndex:0];
    //create a destination file name to write the data :
    NSString *fullFileName = [NSString stringWithFormat:@"%@/managers", cacheDirectory];
    NSDictionary* panelLibraryContent = [NSDictionary dictionaryWithContentsOfFile:fullFileName];
    if (panelLibraryContent != nil) {
        // load was successful do something with the data...
    } else {
        // error while loading the file
    }   
}

-(void) storeDictionary:(NSDictionary*) dictionaryToStore {
    //get the documents directory:
    NSArray *paths = NSSearchPathForDirectoriesInDomains
    (NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDirectory = [paths objectAtIndex:0];
    //make a file name to write the data to using the
    //cache directory:
    NSString *fullFileName = [NSString stringWithFormat:@"%@/managers", cacheDirectory];

    if (dictionaryToStore != nil) {
        [dictionaryToStore writeToFile:fullFileName atomically:YES];
    }
} 

无论如何,这种方法非常有限,如果您想存储更复杂的数据,则必须花费大量额外的工作。在这种情况下,CoreData API非常方便。

答案 2 :(得分:5)

在Swift中:

<强>设置

let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(value, forKey: key)

// userDefaults.setFloat(12.34, forKey: "myFloatKey")
// userDefaults.setBool(true, forKey: "myBoolKey")

请注意,对于iOS 8及更高版本,调用userDefaults.synchronize()not recommended

<强>获取

let userDefaults = NSUserDefaults.standardUserDefaults()
if let value = userDefaults.objectForKey(key) {
    print(value)
}

请注意,userDefaults.boolForKeyuserDefaults.floatForKey都返回非可选值,因此它们永远不会是nil(仅false0.0)。

进一步阅读

答案 3 :(得分:2)

您正在寻找NSUserDefaults

答案 4 :(得分:0)

Swift 4 / Linux

显然有些事情发生了变化。现在有UserDefault课程。 请查看以下链接:

https://developer.apple.com/documentation/foundation/userdefaults

https://www.hackingwithswift.com/read/12/2/reading-and-writing-basics-userdefaults