Question

I'm fairly new to obj-c and cocoa so please bear with me:

I have a NSTableView set up with cocoa bindings which works as expected with the simple -add -remove, etc methods provided by an instance of NSArrayController in my nib. I would like to programmatically add objects to the array that provides content for this controller (and hence for the table view) and then update the view accordingly.

I current have a working method for adding a new object to the array (verified by NSLog) but I can't figure out how to update the table view.

So: How do I update the bound tableview? (ie, after I have programmatically added objects to my array). I'm essentially after some view refreshing code like [view reloadData] in glue code, but I want it to work with the bindings I have in place.

Or is there a KVC/KVO related solution to this problem?

Code Details: AppController.h

@interface AppController : NSObject

@property NSMutableArray *clientsArray;

-(IBAction)addClientFooFooey:(id)sender;

@end

AppController.m (note, I also have the appropriate init method not shown here)

@implementation AppController
...

-(IBAction)addClientFooFooey:(id)sender{
    [self.clientsArray addObject:[[Client alloc] initWithFirstName: @"Foo" andLastName:@"Fooey"]];

//Need some code to update NSTableView here

}

@end

Client.h just simply defines two properties: firstName and lastName. The 2 columns of an NSTableView in my mainmenu.nib file are appropriately bound to these properties via an array controller bound to my AppController instance.

On a side note/as an alternative. How could I add functionality to the existing NSArrayController method -add, ie, something like: -addWithFirstName:andLastName and still have this compatible with bindings?

Was it helpful?

Solution

You have two main options for doing this provided your array controller is bound to clientsArray.

The first way is to just use the array controller's addObject: method instead of adding objects directly to clientsArray.

The other way is to keep your current addClientFooFooey: method but wrap your existing code with these two lines:

[self willChangeValueForKey:@"clientsArray"];

[self didChangeValueForKey@"clientsArray"];

This tells the KVO system that you are making a change to the array so it will go and look at it again.

The first option is the most straightforward, but if for some reason you need to update the array directly just let KVO know you are doing it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top