Saturday, July 26, 2008

NSTableView - updating the view



The problem I want to solve next is to update an NSTableView using bindings. That is, given a change to the underlying data, we want the view to update automatically. However, if we make the change directly, it won't propagate to the view. I haven't yet read the Cocoa Bindings Programming Topics, so maybe the answer is somewhere in that document, but I haven't found it by skimming. Instead, I found the answer on a mailing list answer written by Scott Stevenson. (I've lost track of the link). Anyway, he mentioned a function called "mutableArrayValueForKey" which I'd never heard of, and he gave the lines which I've used in my code below. Apparently you can call the function on any KVO compliant object, and use it to update that object's value.

class PyBind6AppDelegate(NSObject):
MA = objc.ivar('MA')

def awakeFromNib(self):
L = [ {'name':'Groucho','uid':'1'},
{'name':'Chico','uid':'2'},
{'name':'Harpo','uid':'3'} ]
self.MA = NSMutableArray.arrayWithArray_(L)

@objc.IBAction
def go_(self,sender):
D = {'name':'Zeppo','uid':'4'}
bindingsArray = self.mutableArrayValueForKey_('MA')
bindingsArray.addObject_(D)
NSLog("%s" % bindingsArray.description())

As usual, I've wired up a button so that I can see what result a particular change triggered by the button makes to the app window. The screenshots shown above are before and after views.

OK. That's enough about bindings for now. I'm going to continue with Hillegass (and read the Apple docs on KVO, KVC and Bindings) and then I'll get back with more.

No comments: