Make a table listing all the keys and values ​​of a dictionary

advertisements

My AppDelegate contains a dictionary. I have an NSDictionaryController bound to dict. I then bind the 2 columns of an NSTableView to the Dictionary Controller:

  • Column 1 (Key): Controller Key = arrangedObjects. Model Key Path = key
  • Column 2 (Value): Controller Key = arrangedObjects. Model Key Path = value

But my table is blank. Any idea how's to correct this?

My code:

class AppDelegate {
    dynamic var dict = NSMutableDictionary()

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        dict.setValue(1, forKey: "One")
        dict.setValue(2, forKey: "Two")
    }
}

I also tried:

let newObject = dictController.newObject()
newObject.setKey("One")  // deprecated
newObject.setValue(1)    // deprecated
dictController.addObject(newObject)

But Xcode said setKey and setValue are deprecated in 10.10.3. How do I add an object to an NSDictionaryController? I'm running Mac OS X 10.11.4.


The dictionary controller doesn't see the changes inside dict. You can solve this by first contructing the dictionary and then assigning to dict.

func applicationDidFinishLaunching(aNotification: NSNotification) {
    var tempDict = NSMutableDictionary()
    tempDict.setValue(1, forKey: "One")
    tempDict.setValue(2, forKey: "Two")
    dict = tempDict
}

Another solution is implementing key-value observer compliance.

func applicationDidFinishLaunching(aNotification: NSNotification) {
    willChangeValueForKey("dict")
    dict.setValue(1, forKey: "One")
    dict.setValue(2, forKey: "Two")
    didChangeValueForKey("dict")
}

Thanks to @Code Different for making me realize what the problem is.