Reputation: 1184
I have an NSTableView which is bound to an NSDictionaryController. I have set this and the content dictionary through the interface builder. The question I have is, how do I add objects to the dictionary in a manner that the controller will see it automatically and display it in the table.
I've seen in examples about NSArrayController that you add the new objects through the controller rather than the actual array so the controller sees the change. However, I don't see a similar way of doing this with the dictionarycontroller...
Thanks for the help.
Upvotes: 2
Views: 2167
Reputation: 1107
Jason's answer can be simplified:
NSDictionaryControllerKeyValuePair *c = myDictionaryController.newObject;
c.key = @"foo";
c.value = @"bar";
[myDictionaryController addObject:c];
Upvotes: 0
Reputation: 933
Excellent! modified for Swift3:
// Use NSDictionaryControllerKeyValuePair Protocol setKey
let temp = myDictionaryController.newObject()
temp.setValue(name, forKey: "key")
temp.setValue(list, forKey: "value")
myDictionaryController.addObject(temp)
Upvotes: 0
Reputation: 49
jasons answer didn't work for me because in my implementation it ran into an error on the line [newObject setValue:@"value"], saying that multiple methods were found with mismatched results and i couldn't find any other method that would add the new entry as intended.
after a lot of searching and trying i came up with this solution: just renew the binding everytime the dictController needs to be updated, like this:
[dictController bind:NSContentDictionaryBinding toObject:self withKeyPath:@"nameOfMyDictionary" options:nil];
so throughout my code i add items to my dictionary, and just before showing the table with the contents of my dictionary i reset the binding. this is probably a dirty solution, but it worked for me.
Upvotes: 0
Reputation: 1184
Well I ended up figuring this out. I figured since the arraycontroller mirrored the use of an array that a dictionarycontroller would do the same but it is not so. The process is a little bit different...
So if you have a dictionarycontroller that you would like to add values to so it can update anything binding to it you use the following process:
//Creates and returns a new key-value pair to represent an entry in the
//content dictionary.
id newObject = [dictController newObject];
//Use NSDictionaryControllerKeyValuePair Protocol setKey
[newObject setKey:@"Key"];
//Use NSDictionaryControllerKeyValuePair Protocol setValue
[newObject setValue:@"value"];
//Add the object to the controller
[dictController addObject:newObject];
This will in effect, update both the dictionarycontroller and add the value to the content dictionary. You cannot use setValue:ForKey in this case because this is not a method implemented in the NSDictionaryControllerKeyValuePair Protocol.
I hope this can help others using these controllers!
Upvotes: 4