Search code examples
xcodemacosapplescriptnsapplescript

Saving variables in applescript using plist's within application xcode


How do I make my script write to a Property List file without having to create a ".plist" file on the user's computer, but rather directly in the current application?


Solution

  • The plist files are created from the user defaults. So you need to save your values there.

    Make a property to shorten writings at top

    property NSUserDefaults : class "NSUserDefaults" of current application
    

    to write

    NSUserDefaults's standardUserDefaults()'s setObject_forKey_(yourValue, yourKey)
    

    to read

    NSUserDefaults's standardUserDefaults()'s object_forKey(yourKey) 
    

    Example

    property NSUserDefaults : class "NSUserDefaults" of current application
    
    set mytext to "Hello"
    
    -- write
    NSUserDefaults's standardUserDefaults()'s setObject_forKey_(mytext, "MyKey")
    
    -- read it with
    log NSUserDefaults's standardUserDefaults()'s object_forKey_("MyKey")
    -- Hello
    

    It's untested cause i don't have a mac here at the moment. But it should work.

    Edit

    To set standard values do the following in your application's appDelegate method applicationWillFinishLaunching:aNotification (don't forget to declare the property mentioned above):

    on applicationWillFinishLaunching:aNotification
        set prefs to {MyKey:"Hello", SomeOtherKey:true}
        NSUserDefaults's standardUserDefaults()'s registerDefaults_(prefs)
    end