Skip to content
jeff-h edited this page May 17, 2014 · 1 revision

getUserDefaultsKeys

Get an array of all user defaults keys. The value of each may be retrieved using one of the four getter functions described below.

macgap.userDefaults.getUserDefaultsKeys();

Get all user defaults set previously by your MacGap JavaScript. Returns a JSON string.

getMyDefaults

macgap.userDefaults.getMyDefaults();

Example usage:

var defaults = JSON.parse( macgap.userDefaults.getMyDefaults() );

setString, setInteger, setBool, setFloat

Set the user default at the specified key. Objective-C is strongly typed, unlike JavaScript. For security, keys are automatically preceded with 'macgap_'. If this is omitted it will be added automatically. Thus the following two statements are functionally identical.

macgap.userDefaults.setString('macgap_mykey', 'mystring');
macgap.userDefaults.setString('mykey', 'mystring');

Examples of setting different data types:

macgap.userDefaults.setInteger('macgap_mykey', 5);
macgap.userDefaults.setBool('macgap_mykey', 1);
macgap.userDefaults.setFloat('macgap_mykey', 12.345678);

getString, getInteger, getBool, getFloat

Get the user default for the specified key. Objective-C is strongly typed, unlike JavaScript.

macgap.userDefaults.getString('macgap_mykey');
macgap.userDefaults.getInteger('macgap_mykey');
macgap.userDefaults.getBool('macgap_mykey');
macgap.userDefaults.getFloat('macgap_mykey');

removeObjectForKey

Remove the user default for the specified key.

macgap.userDefaults.removeObjectForKey('macgap_mykey');

userDefaultsChanged event

Be notified when the user defaults are changed. To see what was changed, store a local snapshot of the object and compare to it. Only items with a key beginning with macgap_ are returned, although any key may have triggered the event. For example, since the window's x,y position is stored in the User Defaults, this event will fire every time the app window is moved.

document.addEventListener('userDefaultsChanged', function(e) {
    console.log(e.data);
}, true);

Notes & hints:

When removing or setting user defaults from JavaScript, the provided key must be prefixed with macgap_. If this is ommitted the key will be automatically namespaced by prefixing macgap_. This ensures it is not possible for JavaScript to modify or delete User Defaults which it did not create, as a security measure.

The User Defaults provide a large amount of interesting data that is now available to your JavaScript app.

They can also be used to implement an easy channel for communication between JavaScript and objects placed into the app using Interface Builder in Xcode eg Toolbars, buttons, preference windows. These can be bound directly to the User Defaults in Interface Builder, without writing any Objective-C code, and controlled directly from JavaScript.