TweetFollow Us on Twitter

The Road to Code: Come Together, Right Now

Volume Number: 24
Issue Number: 10
Column Tag: The Road to Code

The Road to Code: Come Together, Right Now

Combining bindings, document-based applications, and table views

by Dave Dribin

Putting a Few Things Together

This month in The Road to Code, we're going to put together a few concepts we've been working on over the past few months. To start with, we're going to build upon the document-based application we wrote that allowed the user to save and open a document representing a rectangle. We already added archiving and unarchiving support to our Rectangle class by implementing the NSCoding protocol, briefly discussed using an NSTableView to show a list of rectangles, and learned the basics of Cocoa bindings. Now, we are going to combine these three topics to make a document-based application that allows the user to save a list of rectangles and to add and remove rectangles, both with and without Cocoa bindings.

Documents with a Table View

First, let's make sure we're all using the same version of Xcode. Version 3.1 was released in July and is now the current version. I'm going to use it going forward. Now that we're all using the same version of Xcode, let's create a new document-based application called Rectangles. This project template creates a NSDocument subclass, MyDocument, for you to customize. But before we start coding, let's layout the user interface in Interface Builder and work our way back.

Open up the MyDocument.xib file. Interface Builder 3.0 introduced the .xib file format and as of Xcode 3.1, the default file format for Interface Builder files in Apple supplied project templates is .xib instead of .nib. While the file format and extension has changed, they are identical from the developer's perspective: they contain the GUI you develop in Interface Builder. Create a window with a table view that looks similar to Figure 1. Be sure that the area and perimeter labels are two separate text fields, one for the text, e.g. one for "Total Area:" and one for the number, as we need to update the number but leave the text as-is. Set up the autosizing so that the table view expands when the window is resized and use a number formatter for each row's text cell and the two area and perimeter number text fields.


Figure 1: Window in Interface Builder

The table view needs a bit more customization. First, turn off column selection, as we do not want the user to select individual columns. Next, customize each column's identifier and disable editing of the area and perimeter columns. The correct settings are summarized in Table 1. It is important to use all lower-case for the identifier.


With our user interface created, switch back to Xcode. Be sure to enable garbage collection in the build settings for the Rectangles target before continuing. All the code we are writing requires garbage collection, and it is not the default setting.

Add in the Rectangle class with NSCoding support that we created in the July 2008 issue, One for the Archives, which you can download from the MacTech website. In our MyDocument class, we first need to create outlets for the table view, the Total Area and Total Perimeter labels, and actions for the Add and Remove buttons. We also want to create a mutable array instance variable that will hold all rectangle instances. The resultant header file for MyDocument is shown in Listing 1.

Listing 1: MyDocument.h

#import <Cocoa/Cocoa.h>
@interface MyDocument : NSDocument
{
    IBOutlet NSTableView * _tableView;
    IBOutlet NSTextField * _totalAreaLabel;
    IBOutlet NSTextField * _totalPerimeterLabel;
    
    NSMutableArray * _rectangles;
}
- (IBAction)addRectange:(id)sender;
- (IBAction)removeRectangle:(id)sender;
@end

Switch to the implementation file, MyDocument.m. Modify the constructor to create the _rectangles array as follows:

- (id)init
{
    self = [super init];
    if (self == nil)
        return nil;
    
    _rectangles = [[NSMutableArray alloc] init];
    
    return self;
}

Also add these three methods for the actions:

- (void)updateTotalAreaAndPerimeter
{
    float totalArea = 0;
    float totalPerimeter = 0;
    for (Rectangle * rectangle in _rectangles)
    {
        totalArea += rectangle.area;
        totalPerimeter += rectangle.perimeter;
    }
    
    [_totalAreaLabel setFloatValue:totalArea];
    [_totalPerimeterLabel setFloatValue:totalPerimeter];
}
 
- (IBAction)addRectange:(id)sender
{
    Rectangle * rectangle = [[Rectangle alloc] initWithLeftX:0
                                                     bottomY:0
                                                      rightX:15
                                                        topY:10];
    [_rectangles addObject:rectangle];
    
    // Update the UI
    [_tableView reloadData];
    [self updateTotalAreaAndPerimeter];
}
- (IBAction)removeRectangle:(id)sender
{
    NSInteger selectedIndex = [_tableView selectedRow];
    // If no row is selected, don't do anything
    if (selectedIndex == -1)
        return;
    
    [_rectangles removeObjectAtIndex:selectedIndex];
    
    // Update the UI
    [_tableView reloadData];
    [self updateTotalAreaAndPerimeter];
}

Taking a closer look at these three methods, the addRectangle: method creates a new 15x10 rectangle and adds it to the array of rectangles. It then has to update the user interface so that it matches the array. The reloadData method of NSTableView causes the table view to refresh its contents from its data source. We also need to update the area and perimeter labels. We created the updateTotal-AreaAndPerimeter method to calculate the total area and perimeter and update the labels.

The removeRectangle: action removes the currently selected rectangle. It asks the table view for the selected row index and uses this to remove the correct rectangle. Again, it updates the user interface to match the array.

That's all for coding, at the moment. Save your modifications and build the project, making sure to fix any syntax errors. Now, switch to Interface Builder because we need to connect our outlets and actions. Connect the outlets to their corresponding components, and connect the buttons to the two actions methods.

At this point, our application will run, and the buttons will work, but the table view will not be correctly populated with data. We need to use the table view's data source to populate the data. While we're in Interface Builder, set MyDocument to be the data source by connecting the NSTableView's dataSource outlet to File's Owner, which represents MyDocument. Switch back to Xcode and add these three required data source methods:

#pragma mark -
#pragma mark Table view data source
- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
    return [_rectangles count];
}
- (id)tableView:(NSTableView *)tableView
objectValueForTableColumn:(NSTableColumn *)tableColumn
            row:(NSInteger)rowIndex
{
    Rectangle * rectangle = [_rectangles objectAtIndex:rowIndex];
    NSString * identifier = [tableColumn identifier];
    float value = 0;
    if ([identifier isEqualToString:@"width"])
        value = rectangle.width;
    else if ([identifier isEqualToString:@"height"])
        value = rectangle.height;
    else if ([identifier isEqualToString:@"area"])
        value = rectangle.area;
    else if ([identifier isEqualToString:@"perimeter"])
        value = rectangle.perimeter;
    
    return [NSNumber numberWithFloat: value];
}
- (void)tableView:(NSTableView *)tableView
   setObjectValue:(id)object
   forTableColumn:(NSTableColumn *)tableColumn
             row:(int)rowIndex
{
    Rectangle * rectangle = [_rectangles objectAtIndex:rowIndex];
    NSString * identifier = [tableColumn identifier];
    
    float value = [object floatValue];
    if ([identifier isEqualToString:@"width"])
        rectangle.width = value;
    else if ([identifier isEqualToString:@"height"])
        rectangle.height = value;
    // Update the UI
    [self updateTotalAreaAndPerimeter];
}

We are using the column identifier to get or set the correct value from the Rectangle instance. Because the NSTableView data source deals only with objects, we need to convert the float values to and from NSNumbers. Now our application should run, and you should be able to add rectangles, modify their width or height, and remove rows. Figure 2 shows an example screen shot.


Figure 2: Screen Shot

The final detail missing from our application is the ability to save and open a custom document type. As we did in One for the Archives, we need to override two methods in our NSDocument subclass:

- (NSData *)dataOfType:(NSString *)typeName
                 error:(NSError **)outError
{
    NSData * rectangleData =
    [NSKeyedArchiver archivedDataWithRootObject:_rectangles];
    return rectangleData;
}
 - (BOOL)readFromData:(NSData *)data
              ofType:(NSString *)typeName
               error:(NSError **)outError
{
    _rectangles = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return YES;
}

These method implementations are very easy because both NSMutableArray and Rectangle support archiving via NSCoding. An array just archives each object in turn. We also have to set up the document types for our application. Open the Info panel on the Rectangles target and add a "rectangles" extension to the first document type as shown in Figure 3.


Figure 3: Rectangles target info

We now have a document-based application that can save and open an array of rectangles. This is not much different than the document-based application we wrote a few months ago, but it does show how to use a mutable array as the data source for a table view. We are going to be making some modifications to this application, culminating in the creation of a Cocoa bindings version.

Utilizing Key-Value Coding

The first step is to modify the data source accessor methods to be a little more flexible. Currently, they are big if statements based on the column identifier. Adding or changing columns requires changing these data source methods to match the changes we make in Interface Builder.

The simplest way to do this is to use key-value coding (KVC) to get and set the rectangle's properties in the data source. While identifiers are generally arbitrary, we are going to give them special meaning. For this to work, we are going to use key names as the column identifiers. Assuming you used the identifiers I recommended in Table 1, you are all set to go. Modify the data source methods as follows:

- (id)tableView:(NSTableView *)tableView
objectValueForTableColumn:(NSTableColumn *)tableColumn
            row:(NSInteger)rowIndex
{
    Rectangle * rectangle = [_rectangles objectAtIndex:rowIndex];
    NSString * identifier = [tableColumn identifier];
    return [rectangle valueForKey:identifier];
}
- (void)tableView:(NSTableView *)tableView
   setObjectValue:(id)object
   forTableColumn:(NSTableColumn *)tableColumn
              row:(int)rowIndex
{
    Rectangle * rectangle = [_rectangles objectAtIndex:rowIndex];
    NSString * identifier = [tableColumn identifier];
    [rectangle setValue:object forKey:identifier];
    // Update the UI
    [self updateTotalAreaAndPerimeter];
}

In objectForTableColumn:, we use valueForKey: to retrieve the appropriate property. If our identifiers did not match their corresponding property names, we would get a runtime error. Notice that we do not have to convert the float values into NSNumber objects either, as KVC automatically does this for us. The setObjectValue: method conversely uses setValue:forKey: to set the appropriate property given the object value.

Switching to Cocoa Bindings

Using KVC in the data source is the first step towards using Cocoa bindings. Looking at the data source code now, it's barely specific to our application. We could take this code wholesale on a new project and use it almost without modification. The trick is to use KVC key names as the table column identifiers. Cocoa bindings takes this to the next logical step and provides reusable controllers based on KVC to eliminate repetitious controller code.

Last month, we used NSObjectController as the controller for a single Rectangle instance. However, now we have an array of Rectangles we want need to manage, and NSObjectController will no longer work. Thankfully, the NSArrayController is just what we need. This is a reusable controller for managing an ordered list of objects.

To use an array controller, find it in Interface Builder's Library window, and drag it over to the MyDocument.xib window. The array controller's icon in the Library panel is shown in Figure 4.


Figure 4: Array Controller in the Library Panel

Rename the array controller to Rectangles, as shown in Figure 5. Set the Class Name of the controller to Rectangle and check the Prepares Content option as shown in Figure 6. The class name is important because our array controller can add objects to the array. If it does not use the correct class, our code will no longer work properly.


Figure 5: Array Controller in XIB window


Figure 6: Array Controller Attributes

Now it's time to configure the table columns to use bindings. Let's start with the width column. Bind the column to the Rectangles controller with a Controller Key of arrangedObjects and a Model Key of width, as summarized in Figure 7. The arrangedObjects controller key represents each object in the ordered list. When used in a table view, it will use the row index to find the correct object in the ordered list, just as we did in our data source methods. The model key tells this column to use the width property as the value. It's important to use arrangedObjects because an array controller can re-sort the objects in the list without affecting the original array. An example of this is when the user clicks on a table header.


Figure 7: Width column bindings

Repeat the bindings for each of the columns. The controller and Controller Key are the same for all columns, but change the Model Key to be the appropriate property name. The model key should be the same as the identifier we used earlier, as it gets used with KVC by the array controller.

At this point you can delete the three data source methods from our MyDocument class and disconnect the data source outlet of the table view. We are now using bindings to populate the table view rather than using the data source. We also have to modify our add and remove actions to work in a KVC-compliant manner:

- (IBAction)addRectange:(id)sender
{
    Rectangle * rectangle = [[Rectangle alloc]
 initWithLeftX:0
                                              
      bottomY:0
                                               
       rightX:15
       
         topY:10];
    [[self mutableArrayValueForKey:@"rectangles"]
     addObject:rectangle];
}
- (IBAction)removeRectangle:(id)sender
{
    NSInteger selectedIndex = [_tableView selectedRow];
    // If no row is selected, don't do anything
    if (selectedIndex == -1)
        return;
    
    [[self mutableArrayValueForKey:@"rectangles"]
     removeObjectAtIndex:selectedIndex];
}

The issue is that we cannot modify the _rectangles array directly because the array controller will not notice the updates. The array controller uses key-value observing (KVO) to monitor changes to the model and update the view. When you modify the array directly, you are not doing it in a way that triggers KVO notifications. By using mutableArrayValueForKey:, we are given a mutable array proxy to the "rectangles" key that sends proper KVO notifications. This is probably one of the most common issue newbies have with Cocoa bindings. There are other ways to modify the "rectangles" key in a KVO-compliant manner, but using this array proxy is the easiest.

We are not quite finished. Our actions no longer use the updateTotalAreaAndPerimeter method, and we can delete it, but we still need some way to update the total area and perimeter labels. We are going to use bindings for these, too. Switching back to Interface Builder, select the total area number text field. Bind it to the Rectangles controller and the arrangedObjects controller key, just as you did for the table columns; however, for the Model Key Path, use the string @sum.area as shown in Figure 8.


Figure 8: Total Area binding

Since arrangedObjects is an array of objects, we cannot directly use it for a text field, which only displays one object. The "@sum" string is known as a collection operator. It takes the next key path, in this case "width," and calculates the total sum of each value. Thus, the binding of "arrangedObjects.@sum.width" automatically calculates the total width for us without any code. Similarly the total perimeter text field should be bound to the @sum.perimeter model key path.

There are other collection operators, including "@count", "@min", and "@max" that calculates the number of items in array, the minimum value, and maximum value respectively. These collection operators allow us to use Cocoa bindings where we previously had to write controller code. In this case, it replaces our updateTotalAreaAndPerimeter method, and it does so in a KVO-compliant manner. If any of the rectangles in the array changes, the total will automatically be updated using KVC/KVO. Well, almost automatically.

If you copied the Rectangle class from the July issue, as I suggested earlier, it will not have the dependent keys defined. Just as we did in last month's article, we need to add these two methods to the Rectangle class:

+ (NSSet *)keyPathsForValuesAffectingArea
{
    return [NSSet setWithObjects:@"width", @"height", nil];
}
+ (NSSet *)keyPathsForValuesAffectingPerimeter
{
    return [NSSet setWithObjects:@"width", @"height", nil];
}

This makes the area and perimeter dependent on the width and height. Thus, when the user edits the width of one of the rectangles in the table, it causes KVO notifications to be sent for the width and then the area and perimeter. These area and perimeter KVO notifications then trigger the total area and perimeter labels to be recalculated.

But wait...there's more!

Cocoa-bindings has allowed use to get rid of the table view data source and other GUI updating code. But we can also get rid of our action methods. The array controller has add and remove action methods we can use. Switching back to Interface Builder, control drag from the Add button to the Rectangles array controller and choose add: action from the popup. Similarly, connect the Remove button to the remove: action.

The array controller also allows us to enable and disable the Add and Remove buttons properly. For example, when there is no selected row, the Remove button should be disabled. You can do this by binding the Enabled property of the buttons. Bind the Enabled property of the Add button to the canAdd controller key, as shown in Figure 9. Also bind the Enabled property of the Remove button to the canRemove controller key.


Figure 9: Add button Enabled binding

If we run our application with these actions and bindings to the array controller, the application still works. The Remove button even gets disabled when no row is selected. However, there is one issue. Now our new rectangles are all created with zero width and height. This is because the array controller just calls the init method on the new Rectangle object. For the Rectangle class, the default constructor just sets all instance variables to zero. There are a few ways to remedy this situation:

modify the Rectangle model class to have different default values in the default constructor,

subclass NSArrayController and override the newObject method, or

use our own custom add action.

I don't generally like modifying the Rectangle class to satisfy the UI as it's putting logic that should be part of the view (the UI) into the model class. What if a different user interface wanted different default values? To me, the default values should be part of the controller layer, not the model. But every case is different, and sometimes putting default values inside the model is fine. Since our application's default of a 15x10 rectangle seems specific to our UI, I don't think the model is the correct place to put it.

This leaves us with subclassing NSArrayController or adding our own custom action method. Neither of these methods is absolutely better than the other, so you could go either way. The downside to the subclassing NSArrayController is that you are creating a new class with just a single method. Keeping the custom action part of the controller may keep related code together in the same class, leading to better code organization. If you want to use the custom action alternative, keep the addRectangle: action method we had previously.

For completeness, I'm going to show you how to subclass NSArrayController, as it is a common technique you are likely come across. Create a new Objective-C class in your project and name it RectanglesController. Modify the header file so that it matches Listing 2.

Listing 2: RectanglesController.h

#import <Cocoa/Cocoa.h>
@interface RectanglesController : NSArrayController
{
}
@end

We don't need to declare any new instance variables or methods, so the interface is pretty sparse. The implementation contains just one method, as shown in Listing 3.

Listing 3: RectanglesController.m

#import "RectanglesController.h"
#import "Rectangle.h"
@implementation RectanglesController
- (id)newObject
{
    Rectangle * rectangle = [super newObject];
    rectangle.width = 15;
    rectangle.height = 10;
    return rectangle;
}
@end

The newObject method is called whenever the array controller needs to create a new object. We are going to call on the superclass's implementation to create the new rectangle, but then we are going to set the width to 15 and height to 10 just as we did earlier. Now we need to use our subclass in Interface Builder. Do this by selecting the Rectangles controller from the MyDocument.xib window and switching to the Identity tab of the Inspector panel. Change the Class field from NSArrayController to RectanglesController, as shown in Figure 10. This tells Interface Builder to create an instance of our array controller subclass instead of the standard Cocoa array controller.


Figure 10: NSArrayController Subclass

Now, when you run the application, the new rectangles should have a default width and height of 15x10. As I mentioned, there's not a huge advantage to doing this over creating a custom add action method, so do whichever you prefer. The only "trick" to the custom action method is making sure you modify the _rectangles array in a KVC-compliant manner as I showed you earlier.

Conclusion

That wraps up another article on The Road to Code. We've taken what we've learned over the last few months and created a full-featured document-based application with a table view and Cocoa bindings. You should be proud! We've come a long way since the beginning, and you can accomplish quite a bit with what you have learned.


Dave Dribin has been writing professional software for over eleven years. After five years programming embedded C in the telecom industry and a brief stint riding the Internet bubble, he decided to venture out on his own. Since 2001, he has been providing independent consulting services, and in 2006, he founded Bit Maki, Inc. Find out more at http://www.bitmaki.com/ and http://www.dribin.org/dave/.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.