Search code examples
databaseapplescript-objc

How to store values even after the application restarts?


When creating applications with ApplescriptObjC you can create a property like this:

property myValue : "value"

However, if I change the value of this variable, it will get set back to "value" whenever the application restarts. How can I store values so they do not get reset after the application restarts?


Solution

  • You'll need to store your value somewhere before your application quits. Using NSUserDefaults is the best approach:

    property NSUserDefaults : ((current application)'s NSUserDefaults's standardUserDefaults)
    

    To save your value, use the following code, where myKey can be any string, and val is the value that you want to save:

    NSUserDefaults's setObject:val forKey:myKey
    

    To retrieve your value later on, you can use:

    NSUserDefaults's objectForKey:myKey
    

    By the way, NSUserDefaults has several useful functions for getting values, depending on the type of data stored. For example, if you were storing a boolean, you could use "boolForKey:".

    However, you should set a default value for your key, in case it has never been saved before. This must be done before trying to retrieve the value for your key, where defVal is the default value:

    NSUserDefaults's registerDefaults:((current application)'s NSDictionary's dictionaryWithObject:defVal forKey:myKey)
    

    If you'd like to know more about NSUserDefaults, you can read about it here: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/