Search code examples
objective-cmacoscocoansuserdefaultscocoa-bindings

NSUserDefault Registered defaults initial display in NSMenuItem bindings


What is the order of operations you need to execute in order for NSMenuItem(s) that are bound to NSUserDefault keys to display the registered default values?

I am registering the default values, but my NSMenuItems are not showing up with the default's that I registered when I launch my app.


Solution

  • I spent most of the morning chasing this down, and most of the answers out there seem to be fragmentary, so thought I would share.

    1) Bind your menu items to:

    • Shared User Defaults
    • Controller Key:values
    • Model Key Path:keyName (in this case Deduplication_Target)

    2) Register your defaults before awakeFromNib gets called, I did it in the + (void)initialize method in my AppDelegate. (applicationDidFinishLaunching, (id)init, applicationWillFinishLaunching, none of these worked)

    + (void)initialize {
        [self setupDefaults];
    }
    

    3) Initialize your defaults dictionary with NSNumbers for BOOL values, despite examples out there that show them initialized as NSStrings:

    NSString *const KEY_DEDUPLICATION_TARGET = @"Deduplication_Target";
    NSString *const KEY_DEDUPLICATION_SOURCE = @"Deduplication_Source";
    + (void)setupDefaults {    
        NSDictionary* userDefaultsValuesDict = [NSDictionary dictionaryWithObjectsAndKeys: 
                                               [NSNumber numberWithBool:YES], KEY_DEDUPLICATION_TARGET, 
                                                [NSNumber numberWithBool:YES], KEY_DEDUPLICATION_SOURCE, 
                                                nil];
    
        // set them in the standard user defaults
        [[NSUserDefaults standardUserDefaults] registerDefaults:userDefaultsValuesDict];
    }
    

    That solved it for me.

    For reference: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaBindings/Concepts/NSUserDefaultsController.html