开发者

How do I save user preferences for my iPhone app?

开发者 https://www.devze.com 2023-01-13 05:11 出处:网络
The question title pretty much gives it away - I\'d like my app to remember a few things. It\'s 开发者_StackOverflow社区some sort of calculator, so it should save the last used values and some user se

The question title pretty much gives it away - I'd like my app to remember a few things. It's 开发者_StackOverflow社区some sort of calculator, so it should save the last used values and some user selectable settings.

Basically I'd like to save a handful of floats and BOOLs and load them again the next time the app loads.

What's the best and easiest way to do that?

Thanks!!


One of the easiest ways would be saving it in the NSUserDefaults:

Setting:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

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

Getting:

[[NSUserDefaults standardUserDefaults] objectForKey:key];

– boolForKey:

and

– floatForKey: in your case.


Besides the very good NSUserDefaults approach, there is another easy way to store data from an NSArray,NSDictionary or NSData in a file. You can use these methods as well:

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

respectively (for a NSDictionary):

+ (id)dictionaryWithContentsOfFile:(NSString *)path

you just have to give a valid path to a location. According to the iOS Application Programming Guide, the /Library/Caches directory would be the best place to store data that you need to persist between app launches. (see here)

In order to store/load a dictionary from a filed called "managers" in your document directoy you could use these methods:

-(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];
    }
} 

Anyway this approach is very limited and you have to spend a lot of extra work if you want to store more complex data. In that case the CoreData API is very very handy.


In Swift:

Setting

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

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

Note that for iOS 8 and later, calling userDefaults.synchronize() is not recommended.

Getting

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

Note that userDefaults.boolForKey and userDefaults.floatForKey both return non optional values, so they would never be nil (only false or 0.0).

Further reading

  • NSUserDefaults — A Swift Introduction


You are looking for NSUserDefaults


Swift 4 / Linux

Apparently something has changed. Now there's the UserDefault class. Check these links:

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消