KVC/KVO and bindings: why am I only receiving one change notification? - cocoa

I'm seeing some quirky behaviour with Cocoa's KVC/KVO and bindings. I have an NSArrayController object, with its 'content' bound to an NSMutableArray, and I have a controller registered as an observer of the arrangedObjects property on the NSArrayController. With this setup, I expect to receive a KVO notification every time the array is modified. However, it appears that the KVO notification is only sent once; the very first time the array is modified.
I set up a brand new "Cocoa Application" project in Xcode to illustrate the problem. Here is my code:
BindingTesterAppDelegate.h
#import <Cocoa/Cocoa.h>
#interface BindingTesterAppDelegate : NSObject <NSApplicationDelegate>
{
NSWindow * window;
NSArrayController * arrayController;
NSMutableArray * mutableArray;
}
#property (assign) IBOutlet NSWindow * window;
#property (retain) NSArrayController * arrayController;
#property (retain) NSMutableArray * mutableArray;
- (void)changeArray:(id)sender;
#end
BindingTesterAppDelegate.m
#import "BindingTesterAppDelegate.h"
#implementation BindingTesterAppDelegate
#synthesize window;
#synthesize arrayController;
#synthesize mutableArray;
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
NSLog(#"load");
// create the array controller and the mutable array:
[self setArrayController:[[[NSArrayController alloc] init] autorelease]];
[self setMutableArray:[NSMutableArray arrayWithCapacity:0]];
// bind the arrayController to the array
[arrayController bind:#"content" // see update
toObject:self
withKeyPath:#"mutableArray"
options:0];
// set up an observer for arrangedObjects
[arrayController addObserver:self
forKeyPath:#"arrangedObjects"
options:0
context:nil];
// add a button to trigger events
NSButton * button = [[NSButton alloc]
initWithFrame:NSMakeRect(10, 10, 100, 30)];
[[window contentView] addSubview:button];
[button setTitle:#"change array"];
[button setTarget:self];
[button setAction:#selector(changeArray:)];
[button release];
NSLog(#"run");
}
- (void)changeArray:(id)sender
{
// modify the array (being sure to post KVO notifications):
[self willChangeValueForKey:#"mutableArray"];
[mutableArray addObject:[NSString stringWithString:#"something"]];
NSLog(#"changed the array: count = %d", [mutableArray count]);
[self didChangeValueForKey:#"mutableArray"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
NSLog(#"%# changed!", keyPath);
}
- (void)applicationWillTerminate:(NSNotification *)notification
{
NSLog(#"stop");
[self setMutableArray:nil];
[self setArrayController:nil];
NSLog(#"done");
}
#end
And here is the output:
load
run
changed the array: count = 1
arrangedObjects changed!
changed the array: count = 2
changed the array: count = 3
changed the array: count = 4
changed the array: count = 5
stop
arrangedObjects changed!
done
As you can see, the KVO notification is only sent the first time (and once more when the application exits). Why would this be the case?
update:
Thanks to orque for pointing out that I should be binding to the contentArray of my NSArrayController, not just its content. The above posted code works, as soon as this change is made:
// bind the arrayController to the array
[arrayController bind:#"contentArray" // <-- the change was made here
toObject:self
withKeyPath:#"mutableArray"
options:0];

First, you should bind to the contentArray (not content):
[arrayController bind:#"contentArray"
toObject:self
withKeyPath:#"mutableArray"
options:0];
Then, the straightforward way is to just use the arrayController to modify the array:
- (void)changeArray:(id)sender
{
// modify the array (being sure to post KVO notifications):
[arrayController addObject:#"something"];
NSLog(#"changed the array: count = %d", [mutableArray count]);
}
(in a real scenario you'll likely just want the button action to call -addObject:)
Using -[NSMutableArray addObject] will not automatically notify the controller. I see that you tried to work around this by manually using willChange/didChange on the mutableArray. This won't work because the array itself hasn't changed. That is, if the KVO system queries mutableArray before and after the change it will still have the same address.
If you want to use -[NSMutableArray addObject], you could willChange/didChange on arrangedObjects:
- (void)changeArray:(id)sender
{
// modify the array (being sure to post KVO notifications):
[arrayController willChangeValueForKey:#"arrangedObjects"];
[mutableArray addObject:#"something"];
NSLog(#"changed the array: count = %d", [mutableArray count]);
[arrayController didChangeValueForKey:#"arrangedObjects"];
}
There may be a cheaper key that would give the same effect. If you have a choice I would recommend just working through the controller and leaving the notifications up to the underlying system.

A much better way than explicitly posting whole-value KVO notifications is to implement array accessors and use them. Then KVO posts the notifications for free.
That way, instead of this:
[self willChangeValueForKey:#"things"];
[_things addObject:[NSString stringWithString:#"something"]];
[self didChangeValueForKey:#"things"];
You would do this:
[self insertObject:[NSString stringWithString:#"something"] inThingsAtIndex:[self countOfThings]];
Not only will KVO post the change notification for you, but it will be a more specific notification, being an array-insertion change rather than a whole-array change.
I usually add an addThingsObject: method that does the above, so that I can do:
[self addThingsObject:[NSString stringWithString:#"something"]];
Note that add<Key>Object: is not currently a KVC-recognized selector format for array properties (only set properties), whereas insertObject:in<Key>AtIndex: is, so your implementation of the former (if you choose to do that) must use the latter.

Oh, I was looking for a long time for this solution ! Thanks to all !
After getting the idea & playing around , I found another very fancy way:
Suppose I have an object CubeFrames like this:
#interface CubeFrames : NSObject {
NSInteger number;
NSInteger loops;
}
My Array contains Objects of Cubeframes, they are managed via (MVC) by an objectController and displayed in a tableView.
Bindings are done the common way:
"Content Array" of the objectController is bound to my array.
Important: set "Class Name" of objectController to class CubeFrames
If I add observers like this in my Appdelegate:
-(void)awakeFromNib {
//
// register ovbserver for array changes :
// the observer will observe each item of the array when it changes:
// + adding a cubFrames object
// + deleting a cubFrames object
// + changing values of loops or number in the tableview
[dataArrayCtrl addObserver:self forKeyPath:#"arrangedObjects.loops" options:0 context:nil];
[dataArrayCtrl addObserver:self forKeyPath:#"arrangedObjects.number" options:0 context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
NSLog(#"%# changed!", keyPath);
}
Now, indeed, I catch all the changes : adding and deleting rows, change on loops or number :-)

Related

Why won't the data display in my NSTableView(view based)?

I followed the advice here on how to setup a MainWindowController: NSWindowController for my project's single window. I used a Cocoa class to create the .h/.m files, and I checked the option Also create .xib for User Interface. As a result, Xcode automatically hooked up a window, which I renamed MainWindow.xib, to my MainWidowController.
Next, I deleted the window in the default MainMenu.xib file (in Interface Builder I selected the window icon, then I hit the delete key). After that, I was able to Build my project successfully, and my controller's window in MainWindow.xib displayed correctly with a few buttons on it.
Then I tried adding an NSTableView to my MainWindowController's window. In Xcode, I dragged the requisite delegate and datasource outlets for the NSTableView onto File's Owner, which is my MainWindowController, and I implemented the methods in MainWindowController.m that I thought would make the NSTableView display my data:
- tableView:viewForTableColumn:row:
- numberOfRowsInTableView:
Now, when I Build my project, I don't get any errors, but the data doesn't appear in the NSTableView.
My code is below. Any tips are welcome!
//
// AppDelegate.h
// TableViews1
//
#import <Cocoa/Cocoa.h>
#interface AppDelegate : NSObject <NSApplicationDelegate>
#end
...
//
// AppDelegate.m
// TableViews1
//
#interface AppDelegate ()
#property (weak) IBOutlet NSWindow *window;
#property (strong) MainWindowController* mainWindowCtrl;
#end
#implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
[self setMainWindowCtrl:[[MainWindowController alloc] init] ];
[[self mainWindowCtrl] showWindow:nil];
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Insert code here to tear down your application
}
#end
...
//
// MainWindowController.h
// TableViews1
//
#import <Cocoa/Cocoa.h>
#interface MainWindowController : NSWindowController
#end
...
//
// MainWindowController.m
// TableViews1
//
#import "MainWindowController.h"
#import "Employee.h"
#interface MainWindowController () <NSTableViewDataSource, NSTableViewDelegate>
#property (strong) NSMutableArray* employees;
#property (weak) IBOutlet NSTableView* tableView;
#end
#implementation MainWindowController
- (NSView*)tableView:(NSTableView *)tableView
viewForTableColumn:(NSTableColumn *)tableColumn
row:(NSInteger)row {
Employee* empl = [[self employees] objectAtIndex:row];
NSString* columnIdentifier = [tableColumn identifier];
//The column identifiers are "firstName" and "lastName", which match my property names.
//You set a column's identifier by repeatedly clicking on the TableView until only
//one of the columns is highlighted, then select the Identity Inspector and change the column's 'Identifier' field.
NSString* emplInfo = [empl valueForKey:columnIdentifier]; //Taking advantage of Key-Value coding
NSTableCellView *cellView =
[tableView makeViewWithIdentifier:columnIdentifier
owner:self];
NSLog(#"The Table view is asking for employee: %#", [empl firstName]);
[[cellView textField] setStringValue:emplInfo];
return cellView;
}
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
return [[self employees] count];
}
- (void)windowDidLoad {
[super windowDidLoad];
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
Employee* e1 = [[Employee alloc] initWithFirstName:#"Joe" lastName:#"Blow"];
Employee* e2 = [[Employee alloc] initWithFirstName:#"Jane" lastName:#"Doe"];
[self setEmployees:[NSMutableArray arrayWithObjects:e1, e2, nil]];
//Test to see if the employees array was populated correctly:
Employee* e = [[self employees] objectAtIndex:0];
NSLog(#"Here is the first employee: %#", [e firstName]);
//I see the output: "Here is the first employee: Joe"
}
- (id)init {
return [super initWithWindowNibName:#"MainWindow"];
}
- (id)initWithWindowNibName:(NSString *)windowNibName {
NSLog(#"Clients cannot call -[%# initWithWindowNibName] directly!",
[self class]
);
[self doesNotRecognizeSelector:_cmd];
return nil;
}
#end
...
//
// Employees.h
// TableViews1
#import <Foundation/Foundation.h>
#interface Employee : NSObject
#property NSString* firstName;
#property NSString* lastName;
- initWithFirstName:(NSString*)first lastName:(NSString*)last;
#end
...
//
// Employees.m
// TableViews1
//
#import "Employee.h"
#implementation Employee
- (id)initWithFirstName:(NSString *)first lastName:(NSString *)last {
if (self = [super init]) {
_firstName = first; //I read that you shouldn't use the accessors in init methods.
_lastName = last;
}
return self;
}
#end
File's Owner(=MainWindowController) connections:
NSTableView connections:
Response to comments:
Here is why calling [self tableView] reloadData] at the end of -windowDidLoad, as suggested in the comments, didn't work:
My _tableView instance variable--created by my #property declaration in MainWindowController.m--doesn't point to anything; therefore calling:
[[self tableView] reloadData]
I think is equivalent to calling:
[nil reloadData]
which doesn't do anything.
I never assigned anything to the _tableView instance variable in the -init method, nor did I assign it a value by dragging an outlet somewhere in Interface Builder. To fix that problem, I selected MainWindow.xib (the controller's window) in the Project Navigator(left pane), and then in the middle pane(Interface Builder), I selected the cube representing the File's Owner(selecting the Identity Inspector in the right pane reveals that the File's Owner is the MainWindowController). Then in the right pane, I selected the Connections Inspector, and it revealed an outlet called tableView, which is the IBOutlet variable I declared in MainWindowController.m.
Next, I dragged from the tableView outlet onto the TableView in the middle pane:
Doing that assigns the NSTableView object to the _tableView instance variable that was created by my #property declaration in MyWindowControler.m:
#property (weak) IBOutlet NSTableView* tableView;
As an experiment, I disconnected the outlet, then commented out the #property declaration for tableview, and the tableView outlet no longer appeared in the Connections Inspector. Also, if I change the declaration from:
#property (weak) IBOutlet NSTableView* tableView;
to:
#property (weak) NSTableView* tableView;
...then the tableView outlet doesn't appear in the Connections Inspector. That experiment answered a couple of questions I had about whether I should declare a property as an IBOutlet or not: if you need to assign one of the objects in Interface Builder to one of your variables, then declare the variable as an IBOutlet.
Thereafter, calling [self tableView] reloadData] at the end of -windowDidLoad succeeds in populating the TableView. However, I have not seen any tutorials that call reloadData, and even Apple's guide does not do that.
So, I am still puzzled about whether calling -reloadData is a hack or it's the correct way to do things.
Without it, your table view sits there blissfully clueless about your
expectation that it should even bother asking its datasource for data.
I assumed that an NSTableView automatically queries its datasource when it is ready to display itself, and that my code needed to be able to provide the data at that time.
I don't see you sending -reloadData to your table view anywhere. Tacking it onto the end of -windowDidLoad would be a good place. Without it, your table view sits there blissfully clueless about your expectation that it should even bother asking its datasource for data.
For all it knows, the data is simply not ready / available, so why would it try? More importantly, when should it try? It'd be rather rude of it to try whenever it pleases, considering the UI may not have finished loading / connecting to outlets, or its datasource may be in a vulnerable state (like teardown during/after dealloc) and sending datasource requests may result in a crash, etc.
Two things:
1st, set some breakpoints on when you set your employees array in windowDidLoad vs. when the table first attempts to populate itself and your numberOfRowsInTableView implementation gets called. If the latter happens before the former, then you'll need to add a reloadData after you create your array.
2nd, I personally always use NSCell instead of NSViews for my tables, so I always implement objectValueForTableColumn in my table's datasource. So I'm not sure if there's something different you need to do when you use NSView objects and implement viewForTableColumn. Is there a reason you're not using NSCell?

What does OSX do when I customize an NSTableView cell?

I am trying to customize an NSImageCell for NSTableView using NSArrayController and bindings to change the background of the cell which is selected. So, I created two NSImage images and retain them as normalImage and activeImage in the cell instance, which means I should release these two images when the cell calls its dealloc method. And I override
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
and
- (void) setObjectValue:(id) inObject
But I find that when I click any cell in the tableview, the cell's dealloc method is called.
So I put NSLog(#"%#", self); in the dealloc method and - (void)drawInteriorWithFrame:inView: and I find that these two instance are not same.
Can anyone tell me why dealloc is called every time I click any cell? Why are these two instances not the same? What does OS X do when I customize the cell in NSTableView?
BTW: I found that the -init is called only once. Why?
EDIT:
My cell code
#implementation SETableCell {
NSImage *_bgNormal;
NSImage *_bgActive;
NSString *_currentString;
}
- (id)init {
if (self = [super init]) {
NSLog(#"setup: %#", self);
_bgNormal = [[NSImage imageNamed:#"bg_normal"] retain];
_bgActive = [[NSImage imageNamed:#"bg_active"] retain];
}
return self;
}
- (void)dealloc {
// [_bgActive release]; _bgActive = nil;
// [_bgNormal release]; _bgNormal = nil;
// [_currentString release]; _currentString = nil;
NSLog(#"dealloc: %#", self);
[super dealloc];
}
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
NSLog(#"draw: %#", self);
NSPoint point = cellFrame.origin;
NSImage *bgImg = self.isHighlighted ? _bgActive : _bgNormal;
[bgImg drawAtPoint:p fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
NSPoint strPoint = cellFrame.origin;
strPoint.x += 30;
strPoint.y += 30;
[_currentString drawAtPoint:strPoint withAttributes:nil];
}
- (void) setObjectValue:(id) inObject {
if (inObject != nil && ![inObject isEqualTo:_currentString]) {
[self setCurrentInfo:inObject];
}
}
- (void)setCurrentInfo:(NSString *)info {
if (_currentString != info) {
[_currentString release];
_currentString = [info copy];
}
}
#end
As a normal recommendation, you should move to ARC as it takes cares of most of the memory management tasks that you do manually, like retain, releases. My answers will assume that you are using manual memory management:
Can anyone tell me why dealloc is called every time I click any cell ?
The only way for this to happen, is if you are releasing or auto-releasing your cell. If you are re-using cells, they shouldn't be deallocated.
Why these tow instance are not same ?
If you are re-using them, the cell that you clicked, and the cell that has been deallocated, they should be different. Pay close attention to both your questions, in one you assume that you are releasing the same cell when you click on it, on the second you are seeing that they are different.
What does Apple do when I custom the cell in NSTableView ?
Apple as a company? Or Apple as in the native frameworks you are using? I am assuming you are going for the second one: a custom cell is just a subclass of something that the NSTableView is expecting, it should behave the same as a normal one plus your custom implementation.
BTW: I found that the init is called only once, and why ?
Based on this, you are probably re-using cells, and only in the beginning they are actually being initialised.
It would be very useful to see some parts of your code:
Your Cell's code
Your NSTableView cell's creation code.

Retaining array in subclass

Updated:
I have subclassed UIImageView to make some images movable through touch gestures. In the view controller I have an array holding the initial position of each imageview. My problem is that this array returns null whenever it is called on from the subclass. The idea is to check if the image is in its original position or if it has already been moved before, I have stripped the code to just NSLog what's going on but the problem remains and is driving me nuts.
ViewController.h
NSMutableArray *originalPositions;
#property (nonatomic, retain) NSMutableArray *originalPositions;
-(void)testLogging;
ViewController.m
#synthesize originalPositions;
- (void)viewDidLoad {
originalPositions = [[NSMutableArray alloc]init];
}
-(void)drawImages {
for (int i = 0; i < imagesArray.count; i++) {
CGRect frame = CGRectMake(65 * i, 10, 60, 60);
draggableView *dragImage = [[draggableView alloc] initWithFrame:frame];
NSString* imgName = [imagesArray objectAtIndex:i];
[dragImage setImage:[UIImage imageNamed:imgName]];
[dragImage setUserInteractionEnabled:YES];
[self.view addSubview:dragImage];
NSString *originalPositionAsString = NSStringFromCGPoint(dragImage.center);
[originalPositions addObject:originalPositionAsString];
}
}
-(void)testLogging {
NSLog(#"Logging array: %#", originalPositions);
}
-(IBAction)btnClicked {
[self testLogging];
}
When called from the IBAction (or any other way) in the class, the 'testLogging'-method NSLogs the array correctly but if I call the same method from the subclass, it NSLogs null:
Subclass.m
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
ViewController *viewController = [[ViewController alloc] init];
[viewController testLogging];
}
self.originalPositions = [[NSMutableArray alloc]init];
This already is a memory leak, when you call self.originalPositions = bla then 'bla' will be retained. Thus meaning that the retain count is upped. This means that your mutable array will have a retain count of 2 and that it will leak once your UIImageView is gone.
As for the rest, I wouldn't know what is wrong with your code. My first guess would be that you didn't call populatePositionsArray yet, you should call this whenever your view is created / shown so you are sure the array is populated when touchesBegan is called.
Alternatively you could include an 'if' statement in the touchesBegan that checks whether the array exists and otherwise call the populatePositionsArray to populate it before continueing.
I solved it by writing the array to a plist file after populating it. Not very elegant but working.
Thanks for the help though guys.

Cocoa-bindings and KVO

I have a view MyView, and it has images which I want to bind with an array in my AppDelegate.
MyView class
#interface MyView : NSView {
#private
NSArray *images;
}
#end
+ (void)initialize
{
[self exposeBinding:#"images"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(#"Changed!");
}
My AppDelegate
#property (retain) NSArray *images;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
images = [[NSMutableArray alloc] init];
[view bind:#"images" toObject:self withKeyPath:#"images" options:nil];
// [self addObserver:view forKeyPath:#"images" options:0 context:nil]; // !!!
MyImage *img = [[MyImage alloc] ...];
[self willChangeValueForKey:#"images"];
[[self images] addObject:img];
[self didChangeValueForKey:#"images"];
[img release];
}
Without [self addObserver:view forKeyPath:#"images" options:0 context:nil]; the method observeValueForKeyPath: is never called.
Is it necessary to call addObserver: when using bind:? Does bind: set the KVO? And why doesn't binding work?
What you need is an implemented setter for the images property like below. The most common use-case for this is that you need to invalidate the drawing and request redraw with
-setNeedsDisplay:YES.
- (void)setImages:(NSArray *)newImages
{
if(newImages != images) {
[images release];
images = newImages;
[images retain];
}
[self setNeedsDisplay:YES]; // Addition and only difference to synthesized setter
}
You can drop the -exposeBinding: call, since that has only influence on plugins for Interface Builder, and those where lost with the introduction of Xcode 4.
The reason why the -observeValueForKeyPath:ofObject:change:context: message is not send is that for a binding the observer is not the bound-to object. There is another object in the background. (In the stack form a breakpoint you can see that its class is NSEditableBinder.) So it is correct to register as observer from within the view to the view property #"images".
Another way to get notified about a change in the view is to override -setValue:forKey: method. Then you would need to check the key string and see if it was equal to #"images". But since there are other methods from the KVC protocol like -setValue:forKeyPath:, you would need to be extra careful to not disturb the machinery, i.e. always call super.
Uh. I just realize that my answer so far assumes the easier case where you replace the whole array. Your question was for an array modification. (You do declare an immutable array property in your example, though, which only allows replacement. So keep it as declared, and my approach so far will work. Below I show the other alternative.)
Ok, lets assume you do this in the app delegate, a replacement:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{  
    [view bind:#"images" toObject:self withKeyPath:#"images" options:nil];
    MyImage *img = [[MyImage alloc] ...];
    self.images = [NSArray arrayWithObject:img];
    [img release];
}
You don't need to post the change (using willChangeValueForKey: and didChangeValueForKey:, since you go through the declared property. They do that for you.
Now to the other approach where you modify an array. For that you need to use a mutable array property and modify it through an KVO-notifying proxy, like this:
[self mutableArrayValueForKey:#"images"] addObject:img];
This would pick up the change on the sending (bound-to) side. Then it would be transported to the view through the binding machinery, and eventually set using KVC.
There, on the receiving end in the view, you would need to pick up the property change to #"images". That could be done by overwriting the collection accessor method(s) and do more work there, instead of just accepting the the change. But that is a bit complicated, since there are quite a few accessor methods (See docs). Or, simpler, you could add another observation relationship from within the view.
For that, somewhere in initialization (-awakeFromNib: for example) of the view:
[self addObserver:self forKeyPath:#"images" options:0 context:nil];
and then:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
if([keyPath isEqualToString:#"images"]) {
[self setNeedsDisplay:YES]; // or what else you need to do then.
}
}
Note that this last observer relationship has nothing to do with the binding any longer. The value change to the bound property properly arrives at the view without, you just don't realize (get notified).
That should work.
The only way to have observeValueForKeyPath called is to call addObserver. Binding works through a different mechanism.

Tableview with 2 columns y=mx example

How would I make a tableview with 2 columns (x and y) for a function of y=mx
Ive tried lots of things, all of which end in complete failure.
Can someone please make me a sample code and explain it.
Ive asked and asked and people have directed me to all sorts of tutorials of bool, and how to copy and paste contents, how to save to a file, how to make a list of open applications, none of which help me because they are overly complicated
i have this
//array.m
#import "array.h"
#implementation array
- (IBAction)makeArrays:(id)sender
{
int x,y;
NSNumber *multiplier=[NSNumber numberWithFloat:[mField floatValue]];
for (x=0;x++;x<181)
{
y=[multiplier floatValue]*x;
NSNumber *xValue = [NSNumber numberWithInt:x];
NSNumber *yValue = [NSNumber numberWithInt:x];
NSArray *xArray = [NSArray arrayWithObject:xValue];
NSArray *yArray = [NSArray arrayWithObject:yValue];
}
}
#end
and class file
//array.h
#import <Cocoa/Cocoa.h>
#interface array : NSObject {
IBOutlet id mField;
}
- (IBAction)makeArrays:(id)sender;
#end
where do i go from here?
The first thing you should do in OOP is consider the classes of objects. Cocoa uses an MVC (Model, View, Controller) architecture, so classes should fit in one of these three categories. Cocoa already provides the NSTableView class which works quite well, so that leaves the model and controller.
There are a number of different approaches to the model class you could take:
You could write a function table class that holds x and y values in separate arrays
You could write a function table class that has a single array of (x,y) pairs.
In either this or the previous implementation, you could provide a public interface that supports both arrangements (i.e. they'd have methods that return a y given an x, and properties that are x, y, and (x,y) collections). Some implementation details would depend on how you're connecting the table view to the data (bindings, or the older NSTableViewDataSource protocol).
You could also use an array of x values, and create a value transformer. With this approach, the y-values exist in the table view and not the model.
And so on
The application requirements will determine which approach to take. I'll show you the value transformer approach, as it requires the least amount of code.
For the controller, you could rely on NSArrayController (which works quite well with NSTableView), or create your own. For example, you could use an NSMutableArray as the model, and create a controller that maps the values from the array to other values. This controller could perform the mapping using blocks or some function classes that you define.
As you see, there are quite a few options. I'm going to go with the option that requires the least coding: a value transformer, an NSArrayController for the controller and an NSMutableArray (stored in an object that also stores a value transformer) for the model. In the following, code should be stored in files following the standard convention: each interface and implementation is in a separate file with name equal to the class, and an extension of ".h" for interfaces and ".m" for implementation. I also won't bother with the common import statements, such as for Cocoa/Cocoa.h and each class implementation's own interface.
First, the value transformer. Actually, there are two, an abstract superclass and a concrete subclass. This separation is so that you can easily add other function types later. The superclass, FunctionTransformer, is very simple. All that needs to be overridden from its base, NSValueTransformer, is the method that returns the class of transformed values, transformedValueClass:
#interface FunctionTransformer : NSValueTransformer
+ (Class)transformedValueClass;
#end
#implementation Function
+ (Class)transformedValueClass {
return [NSNumber class];
}
#end
The concrete subclass, LinearTransformer, needs to override the primary method of value transformers: transformedValue:. Since linear transforms are invertible, we'll also provide a reverseTransformedValue:. It will also need properties for the slope and intercept values.
#import "FunctionTransformer.h"
#interface LinearTransformer : FunctionTransformer {
NSNumber *m_;
NSNumber *b_;
}
#property (nonatomic,retain) NSNumber *slope;
#property (nonatomic,retain) NSNumber *intercept;
+ (BOOL)allowsReverseTransformation;
-(id)init;
-(id)initWithSlope:(float)slope;
-(id)initWithIntercept:(float)intercept;
-(id)initWithSlope:(float)slope intercept:(float)intercept;
-(void)dealloc;
-(NSNumber*)transformedValue:(id)value;
-(NSNumber*)reverseTransformedValue:(id)value;
#end
#implementation LinearTransformer
#synthesize slope=m_, intercept=b_;
+(BOOL)allowsReverseTransformation {
return YES;
}
-(id)initWithSlope:(float)m intercept:(float)b {
if ((self = [super init])) {
m_ = [[NSNumber alloc] initWithFloat:m];
b_ = [[NSNumber alloc] initWithFloat:b];
}
return self;
}
-(id)init {
return [self initWithSlope:1.0 intercept:0.0];
}
-(id)initWithSlope:(float)slope {
return [self initWithSlope:slope intercept:0.0];
}
-(id)initWithIntercept:(float)intercept {
return [self initWithSlope:1.0 intercept:intercept];
}
-(void)dealloc {
[b release];
[m release];
[super dealloc];
}
-(NSNumber*)transformedValue:(id)value {
return [NSNumber numberWithFloat:([value floatValue] * [m floatValue] + [b floatValue])];
}
-(NSNumber*)reverseTransformedValue:(id)value {
return [NSNumber numberWithFloat:(([value floatValue] - [b floatValue]) / [m floatValue])];
}
#end
A specific LinearTransformer needs to be registered to be used so that you can set the slope and intercept. The application delegate could own this transformer (along with the x value collection), or you could write a custom controller. We're going to write a model class that bundles together the x values and the value transformer, named FunctionTable. Setting the function transformer requires a sub tasks: registering the transformer as a value transformer (using +setValueTransformer:forName:). This means we'll need to provide our own setter (setF:) for the function transformer property (f).
#import "FunctionTransformer.h"
extern NSString* const kFunctionTransformer;
#interface FunctionTable : NSObject {
NSMutableArray *xs;
FunctionTransformer *f;
}
#property (nonatomic,retain) IBOutlet NSMutableArray *xs;
#property (nonatomic,retain) IBOutlet FunctionTransformer *f;
#end
// FunctionTable.m:
#import "LinearTransformer.h"
NSString* const kFunctionTransformer = #"Function Transformer";
#implementation FunctionTable
#synthesize xs, f;
-(id) init {
if ((self = [super init])) {
xs = [[NSMutableArray alloc] init];
self.f = [[LinearTransformer alloc] init];
[f release];
}
return self;
}
-(void)dealloc {
[f release];
[xs release];
[super dealloc];
}
-(void)setF:(FunctionTransformer *)func {
if (func != f) {
[f release];
f = [func retain];
[NSValueTransformer setValueTransformer:f forName:kFunctionTransformer];
}
}
#end
By default, FunctionTable uses a LinearTransformer. If you want to use a different one, simply set the FunctionTables's f property. You could do this in Interface Builder (IB) by using bindings. Note that in this simplistic implementation, the value transformer is always registered under the name "Function Transformer", effectively limiting you to one FunctionTable. A more complex scheme would be to give every FunctionTable their own function transformer name which would be used when registering their own FunctionTransformer.
To set everything up:
Open the app's main window nib in IB.
Instantiate an NSArrayController and a FunctionTable (and your custom app delegate, if any).
To the main window, add:
Buttons to add and remove elements,
labels and NSTextFields for the slope and intercept,
an NSTableView.
Set the table headers to "x" and "y" (not necessary for app to work)
Set up the connections:
Have the add & remove buttons send to the NSArrayController's add: and remove: actions.
Bind the NSTextFields values to the FunctionTables's f.slope and f.intercept key paths.
Bind the values of both columns of the NSTableView to FunctionTables's xs.
Set the value transformer for the second column to "Function Transformer"
Bind the NSArrayController's content array to the FunctionTable's xs key.
If you've got an app delegate, connect it to the File's Owner's delegate outlet.
Now build and run. You can use the add and remove buttons to add and remove rows to/from the table. You can edit the "x" and "y" column in a row (the latter is thanks to reverseTransformedValue:). You can sort by either the "x" or "y" columns. You can change the slope and intercept, though you won't notice the updates in the table unless you select the rows individually.
Advanced Topics
To fix the table view update problem, we need to propagate changes on one object's (a FunctionTransformer) properties to changes on another's (a FunctionTable) properties. We'll have the FunctionTable observe changes on its function transformer's properties and, when it FunctionTable receives a notice that any such property has changed, send a notice that the xs property has changed (which is a bit of an abuse, since xs hasn't actually changed). This is going to get a little magical, so bear with me.
An object subscribes to changes on another object using the KVO method addObserver:forKeyPath:options:context: of the other object, and unsubscribes using removeObserver:forKeyPath:. These methods just need to be called, not written. Notifications are handled by a observeValueForKeyPath:ofObject:change:context: method of the observing object, so this method needs to be written. Finally, an object can send its own notifications by calling willChangeValueForKey: and didChangeValueForKey:. Other methods exist to send notifications that only part of a collection has changed, but we won't use them here.
Our FunctionTable could handle the change subscription and unsubscription, but then it has to know which properties of the function transformer to observe, which means you couldn't change the type of the transformer. You could add methods to each concrete function transformer to subscribe and unsubscribe an observer:
#implementation LinearTransformer
...
-(void)addObserver:(NSObject *)observer
options:(NSKeyValueObservingOptions)options
context:(void *)context
{
[self addObserver:observer
forKeyPath:#"slope"
options:options
context:context];
[self addObserver:observer
forKeyPath:#"intercept"
options:options
context:context];
}
-(void)removeObserver:(id)observer {
[self removeObserver:observer forKeyPath:#"slope"];
[self removeObserver:observer forKeyPath:#"intercept"];
}
#end
However, this will require a fair bit of code repetition in each method and across each concrete function transformer. Using some magic (reflection and closures, or as they're called in Objective-C, blocks ([2])), we can add the methods (named addObserver:options:context: and removeObserver:, as they are functionally similar to the KVO methods for subscribing & unsubscribing) to FunctionTransformer, or even to NSObject. Since observing all properties on an object isn't just limited to FunctionTransformers, we'll add the methods to NSObject. For this to work, you'll need either OS X 10.6 or PLBlocks and OS X 10.5.
Let's start from the top down, with the changes to FunctionTable. There's now new subtasks when setting the function transformer: unsubscribing from changes to the old transformer and subscribing to changes to the new one. The setF: method thus needs to be updated to make use of NSObject's new methods, which will be defined in a header named "NSObject_Properties.h". Note we don't need to worry about the implementation of these methods yet. We can use them here, having faith that we will write suitable implementations later. FunctionTable also needs a new method to handle change notifications (the observeValueForKeyPath:ofObject:change:context: referred to earlier).
#import "NSObject_Properties.h"
#interface FunctionTable
...
-(void)setF:(FunctionTransformer *)func {
if (func != f) {
[f removeObserver:self];
[f release];
f = [func retain];
[f addObserver:self
options:NSKeyValueObservingOptionPrior
context:NULL];
[NSValueTransformer setValueTransformer:f forName:kFunctionTransformer];
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if (object == f) {
if ([[change objectForKey:NSKeyValueChangeNotificationIsPriorKey] boolValue]) {
[self willChangeValueForKey:#"xs"];
} else {
[self didChangeValueForKey:#"xs"];
}
}
}
Next, we write the new methods on NSObject. The methods to subscribe or unsubscribe from changes will loop over the object's properties, so we'll want a helper method, forEachProperty, to perform the loop. This helper method will take a block that it calls on each property. The subscription and unsubscription methods will simply call forEachProperty, passing a block that calls the standard KVO methods (addObserver:forKeyPath:options:context: and removeObserver:forKeyPath:) on each property to add or remove subscriptions.
//NSObject_Properties.h
#import <Cocoa/Cocoa.h>
#import <objc/runtime.h>
#interface NSObject (Properties)
typedef void (^PropertyBlock)(objc_property_t prop, NSString *name);
-(void)forEachProperty:(PropertyBlock)block;
-(void)addObserver:(id)observer options:(NSKeyValueObservingOptions)options context:(void *)context;
-(void)removeObserver:(id)observer;
#end
// NSObject_Properties.m:
...
#implementation NSObject (Properties)
-(void)forEachProperty:(PropertyBlock)block {
unsigned int propCount, i;
objc_property_t * props = class_copyPropertyList([self class], &propCount);
NSString *name;
for (i=0; i < propCount; ++i) {
name = [[NSString alloc]
initWithCString:property_getName(props[i])
encoding:NSUTF8StringEncoding];
block(props[i], name);
[name release];
}
free(props);
}
-(void)addObserver:(NSObject *)observer
options:(NSKeyValueObservingOptions)options
context:(void *)context
{
[self forEachProperty:^(objc_property_t prop, NSString *name) {
[self addObserver:observer
forKeyPath:name
options:options
context:context];
}];
}
-(void)removeObserver:(id)observer {
[self forEachProperty:^(objc_property_t prop, NSString *name) {
[self removeObserver:observer forKeyPath:name];
}];
}
#end

Resources