Save and load state of button as string (plist-file)

Ok, slowly Im getting into Objc-syntax, but I encountered a problem and neither the forum nor the documentation cant help me out.

In my app the user can save the settings (which are written into a plist-file).
These settings are loaded in awakeFromNib(), which works with TextFields and PopUp buttons.

Now, there is a checkbox and I cant get it to neither save nor load the state.

(write plist)

    on savePlist_(sender)
        tell application "System Events"
            set the parent_dictionary to make new property list item with properties {kind:record}
            set this_plistfile to ¬
            -- some other properties here
            make new property list item at end of property list items of contents of this_plistfile ¬
            with properties {kind:string, name:"copy", value:(checkBox's state() as text)}
        end tell
    end savePlist_

(load plist)


            tell application "System Events"
                tell property list file plistfile_path
                    tell contents
                        -- other properties here
                        checkBox's setState(value of property list item "img")
                    end tell
                end tell

Due to the documentation there are no other options to get or set the state, is my syntax wrong?
Thanks!

Hi,

Cocoa has a built-in class to manage user preferences named NSUserDefaults.
The files are automatically created in ~/Library/Preferences or in the appropriate sandbox library

There are three stages:

¢ Registering defaults to provide default values
¢ Reading defaults
¢ Writing defaults

Registering and reading can be performed in awakeFromNib.
This is an example with an integer value for key “copy” and a string value for key “otherKey”


on awakeFromNib()
	set standardUserDefaults to current application's NSUserDefaults's standardUserDefaults()
	set defaultValues to {|copy|:1, otherKey:"otherValue"}
	standardUserDefaults's registerDefaults_(defaultValues)
	
	checkBox's setState_(standardUserDefaults's integerForKey_("copy"))
	textField's setStringValue_(standardUserDefaults's objectForKey_("otherKey"))
end awakeFromNib

the writing routine can be placed in applicationShouldTerminate or in a separate handler


on writePreferences()
	set standardUserDefaults to current application's NSUserDefaults's standardUserDefaults()
	standardUserDefaults's setInteger_forKey_(checkBox's state(), "copy")
	standardUserDefaults's setObject_forKey_(textField's stringValue(), "otherKey")
	standardUserDefaults's synchronize()
end writePreferences


Consider, that AppleScriptObjC methods which parameters use an underscore character to replace each Objc colon

ObjC

- (void)setInteger:(NSInteger)anInteger forKey:(id)aKey;

AppleScriptObjC equivalent

setInteger_forKey_(anInteger, aKey)

Thanks Stefan,
This works great for me and makes my code much more shorter ! :smiley: