Save (Private) Application Settings on iOS?

前端 未结 3 860
情书的邮戳
情书的邮戳 2021-02-01 17:01

I\'m aware of NSUserDefaults for saving/restoring user preferences. What is the equivalent class for an application

3条回答
  •  后悔当初
    2021-02-01 17:54

    NSUserDefaults can be used for what you're asking.

    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"shownPrompt"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"shownPrompt"];
        // Show your prompt or whatever
    }
    

    That's a working code snippet. If the key is false, it sets it to true and shows the prompt. The next time this code runs, the key will already by true, so the prompt won't be shown.

    NSUserDefaults is specific to the current app on the current device, and is similar to an NSMutableDictionary in that it's a key-value system, with the difference that instead of instantiating your own, there's a universal shared instance for your whole app, that doesn't get erased when the app exits.

    NSUserDefaults is perfect for saving things like whether something has been shown, the date of last run, etc. Read the docs here: https://developer.apple.com/documentation/foundation/userdefaults

    Don't be put off by the 'user preferences' part. You can use it to save anything you want (as long as it is or can be converted to an NSObject which implements , which basically means NSString, NSDictionary, NSArray, NSNumber, UITextField, int, float, bool, etc.).

    Just to clarify, stuff you put in NSUserDefaults will not, under any circumstances, automagically turn up in the Settings app. It will be kept completely private and hidden. For something to appear in Settings, you need to add a Settings bundle to your app, and manually add keys to it for each and every value that you want to be visible in the Settings app.

提交回复
热议问题