Strictly Programming

Cocoa Binding – A simple Example

Posted in Objective-C by sqllyw on 05/26/2010

A very simple example of binding

Update: a new post about binding in XCode 4.6 can be found HERE

Binding is quite similar to Delphi’s data aware components. let’s start a project in XCode 3.x and add following code:


@interface Person : NSObject {
	NSString *name;
	float age;
	BOOL isMarried;


@implementation Person

Modify UntitledAppDelegate.h :

@interface UntitledAppDelegate : NSObject <NSApplicationDelegate> {
    NSWindow *window;
	Person *me;

Modify UntitledAppDelegate.m :

- (id) init;
	me = [Person alloc];
	[me setValue:@"John" forKey:@"name"];
	[me setValue:[NSNumber numberWithFloat:1.5] forKey:@"age"];
	[me setValue:[NSNumber numberWithBool:NO] forKey:@"isMarried"];
	NSLog(@" my name is %@", [me valueForKey:@"name"]);
	return self;

compile and run, you should see following in the console:

[Switching to process 1180]
2010-05-26 09:05:51.523 Untitled[1180:a0f]  my name is John

So far so good. we can see the object ‘me’ is instantiated and values are correctly set. now let’s bind this object ‘me’ to a NSObjectController in IB, it is a three step process:

Drag and drop a NSObjectController into MainMenu.xlib

Define attributes
Specify the class name (Person) under ‘Class Name’, Add keys under Key section, this way you are telling the binding about attributes of class ‘Person’, see the picture:

Bind the controller’s content to a instance of the class
You need to bind the NSObjectController to its content, click the binding page and do as follow,the blue line/arrow is just to show you the linkage, you need to do what in the yellow box to bind the object ‘me’ under controller:

by this time you have finish Model -> Controller, we will address the View layer later.

Now, compile and run, check console, if no error, we proceed to next step:

Attach the views to the controller
Drag and drop two NSLable, one NSCheckBox into main Window under IB, open the first label’s binding page:

do the same for the other two, save, compile and run, you should see:


1. Storage should be allocated in code
2. Specify the attribute of object in NSObjectController.
3. Bind the content to the storage allocated in #1

for the view layer, bind the NSObjectController to the various visual controls.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: