TweetFollow Us on Twitter

Creating a Cocoa AppController Class

Volume Number: 21 (2005)
Issue Number: 1
Column Tag: Programming

Getting Started

by Dave Mark

Creating a Cocoa AppController Class

In our last Cocoa column, we downloaded the latest and greatest version of Xcode. We created a Foundation Tool, which is an Objective-C program with a console-based interface.

This month, we're going to build a Cocoa app with an interface we designed using Interface Builder. The app will use Cocoa's NSSpeechSynthesizer class to speak a line of text. We'll add a pushbutton to start the speech and another to halt it, even in mid-sentence. The example comes from Chapter 4 of Aaron Hillegass' book, Cocoa Programming for Mac OS X. We'll start by taking a look at a class diagramming approach Aaron uses throughout the book.

A Diagram Speaks a Thousand Words

Before we actually start the process of building our project, take a look at the object diagram shown in Figure 1. This diagramming convention was developed by Aaron Hillegas and I find it works quite well at describing the interrelationships between the classes, objects, methods, and instance variables that come together to make your program work.

The class at the heart of this example is the AppController class. Note that this class features two methods: sayIt: and stopIt:. In Hillegas' drawings, each box represents a class and each arrow connecting two boxes represents the control-dragging connection you create in Interface Builder. For example, in Figure 1, note that 4 of the 5 classes are Cocoa classes (they start with NS). All of our code will be built into a new class that we create called AppController. We'll create two instances of NSButton, one labeled Say it and one labeled Stop. Each of the buttons will target one of the two AppController methods. When we build the project in Interface Builder, we'll create an instance of AppController, then control-drag from each button to the AppController instance and double-click on the method we want called to finish the connection.

We'll also add instance variables to AppController to keep track of the NSTextField (so we can retrieve the text to say it) and the NSSpeechSynthesizer (so we can send it the text to start speaking and send it a stop message to halt the speaking).


Figure 1. An object diagram for the first incarnation of our SpeakLine program.

Create the SpeakLine Project

Launch Xcode and create a new project using the Cocoa Application template. Name the project SpeakLine.

Editing the .nib File

In your SpeakLine project file, in the Groups & Files pane, find the file MainMenu.nib and double-click it to launch Interface Builder. You can find the file in the NIB Files group as well as under the SpeakLine group, in the Resources subgroup.

Once Interface Builder launches, click on the third icon from the left in the palette window, then drag an NSTextField from the palette onto the main window. As you can see in Figure 2, the NSTextField is in the upper-left corner of the set of text items.


Figure 2. Dragging out an NSTextField.

Drag the NSTextField so it is almost as wide as the window (so the dashed blue line appears when you get about a scrollbar's width from the right side of the window). Double-click on the text field and change its text to read Peter Piper picked a peck of pickled peppers or, if you are by yourself, perhaps something a bit more spicy.

Next, click on the second icon from the left at the top of the palette window to show the control palette items. Drag two buttons onto the window, below the NSTextField, with the proper spacing between them and the right side of the window. Label the right button Say It and the left button Stop (double-click on a button to edit its label).

Finally, resize the window itself, making it as short as possible. Figure 3 shows my Interface Builder session. In this picture, I am dragging the Stop button into place. You can see the dashed blue lines showing that the two buttons are aligned with each other and that the Stop button is the correct distance from the text field above it and the Say It button to its right.


Figure 3. Use the blue dashed lines to line up your buttons and NSTextField.

Create the AppController Class

Now that your interface is laid out, it's time to create the new AppController class.

Click on the MainMenu.nib window and click on the Classes tab. Scroll all the way to the left and click on the NSObject class. With NSObject highlighted, select Subclass NSObject from the Classes menu. Name the new subclass AppController (see Figure 4).


Figure 4. Click on the NSObject class and select Subclass NSObject from the Classes menu.

Now you'll add two actions (one for each button) and an outlet (an instance variable that points to the text field) to AppController. Open the Info window by selecting Show Info from the Tools menu. Click on the AppController class in the classes tab in the MainMenu.nib window, then click on the Info window and select Attributes from the popup near the top of the Info window.

Click on the Actions tab, then click on the Add button at the bottom right of the Info window. When the new action appears, name it sayIt:, then click Add and name the second action stopIt: (see Figure 5).


Figure 5. The Info window, showing the AppController class attributes.

Next, click on the Outlet tab and click Add to add an outlet named textField to AppController. Click in the Type column and select NSTextField to set the textField type to NSTextField instead of the generic id.

If you look back at Figure 1, you'll see that we've addressed 3 of the 4 arrows in the object diagram. We'll add the missing outlet, speechSynth, in code in just a minute.

Be sure that the AppController class is selected in the Classes tab and select Create Files for AppController from the Classes menu. This will generate two source files (AppController.m and AppController.h) in your Xcode project which we'll edit in a bit.

Next, create an instance of the AppController class by selecting Instantiate AppController from the Classes menu. Interface Builder will switch the MainMenu.nib window to the Instances tab and a new, blue cube will appear with the name AppController.

As you can see in Figure 6, the AppController instance is represented by a blue cube. The tiny exclamation point in a circle to the lower right of the blue cube tells you that there is at least one unconnected outlet. Let's take care of that now.


Figure 6. The new instance of AppController with an unconnected outlet.

Making Connections

Before you start making your connections, take a quick peek back at Figure 1. There are four connections that need to be made. Three of them will be made by control-dragging. The fourth (speechSynth) will be made in code.

First, we'll connect AppController's textField outlet so it points to the NSTextField in the main window. Make sure the Info window is open before you start your drag.

Control-drag from the AppController blue cube to the text field in the main window. When you release the mouse button, the Info window should display its Connections pane and list the textField outlet. Either double-click on the textField line or make sure it is selected and click the Connect button in the lower-right corner of the Info window (Figure 7).


Figure 7. Click the Connect button to connect the AppController to the textField.

Next, we'll connect the two buttons to their respective AppController methods. Control-drag from the Say It button to the AppController cube then, in the Info window, connect to the sayIt: method.

Now control-drag from the Stop button to the AppController cube and connect to the stopIt: method.

NSWindow's initialFirstResponder

The last bit of Interface Builder work we'll do is to set the NSWindow initialFirstResponder outlet to point to the text field. This tells the window that you want the text field to be active when the window appears so you don't have to click in the text field to start typing. To get a feel for this, try running the program with the initialFirstResponder connected and then with it disconnected to see what happens.

Control-drag from the Window icon (to the left of the blue AppController cube) to the text field. In the Info window, click on the initialFirstResponder outlet and click the Connect button.

Now let's type in the code!

Enter the AppController Code

Head back over to Xcode and edit the AppController.h file. We'll add the declaration of speechSynth:


#import <Cocoa/Cocoa.h>


@interface AppController : NSObject 
{
	IBOutlet NSTextField *textField;
	NSSpeechSynthesizer *speechSynth;
} 

- (IBAction)sayIt:(id)sender;
- (IBAction)stopIt:(id)sender; 
@end

Next, edit AppController.m to look like this:

#import "AppController.h"
@implementation AppController

- (id)init 
{  
	[super init];
 	NSLog( @"init" );
 	speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:nil];
	return self; 
 }


- (IBAction)sayIt:(id)sender 
{  
	NSString *string = [textField stringValue];
 if ( [string length] == 0) {   
 	return;  
 }

 [speechSynth startSpeakingString:  string];

 	NSLog( @"Have started to say: %@", string ); 
 }

- (IBAction)stopIt:(id)sender 
{
	NSLog( @"stopping" );
	[speechSynth stopSpeaking]; 
}

- (void)dealloc 
{
	NSLog( @"dealloc" );
	[speechSynth release];
	[super dealloc];
}
@end 

Build and run the application. Notice that you can click the Stop button to stop the speaking, even in the middle.

Take a look through the code. Most of it should make sense, especially if you've been following along with my previous Cocoa columns.

The init: method calls the superclasses' init drops a message to the console, creates an instance of the NSSpeechSynthesizer, then returns a pointer to itself.

sayIt: sends a stringValue message to textField to retrieve the text, then, if there's at least one character in the field, send it via a startSpeakingString message to speechSynth. The string is sent to the console as well, just to help you follow along.

stopIt: sends a message to the console, then sends a stopSpeaking message to speechSynth.

dealloc: is called when the AppController object is released. You'll likely never see the console message, since the AppController object was created automatically and is never sent a release message. When it is loaded from the .nib file, the AppController instance has a ref count of one. Not a big deal, but worth noting.

Till Next Month...

One thing that Aaron does in his book is add a color well to the program so the user can choose their own text color. See if you can do this on your own. You'll want to take advantage of the NSColorWell class.

Be sure to check out http://www.spiderworks.com and I'll see you next month...


Dave Mark is a long-time Mac developer and author and has written a number of books on Macintosh development, including Learn C on the Macintosh, Learn C++ on the Macintosh, and The Macintosh Programming Primer series. Dave's been busy lately cooking up his next concoction. Want a peek? http://www.spiderworks.com.

 
AAPL
$500.59
Apple Inc.
+1.91
MSFT
$34.83
Microsoft Corpora
+0.34
GOOG
$895.27
Google Inc.
+13.26

MacTech Search:
Community Search:

Software Updates via MacUpdate

Apple Canon Laser Printer Drivers 2.11 -...
Apple Canon Laser Printer Drivers is the latest Canon Laser printing and scanning software for Mac OS X 10.6, 10.7 and 10.8. For information about supported printer models, see this page.Version 2.11... Read more
Apple Java for Mac OS X 10.6 Update 17 -...
Apple Java for Mac OS X 10.6 delivers improved security, reliability, and compatibility by updating Java SE 6.Version Update 17: Java for Mac OS X 10.6 Update 17 delivers improved security,... Read more
Arq 3.3 - Online backup (requires Amazon...
Arq is online backup for the Mac using Amazon S3 and Amazon Glacier. It backs-up and faithfully restores all the special metadata of Mac files that other products don't, including resource forks,... Read more
Apple Java 2013-005 - For OS X 10.7 and...
Apple Java for OS X 2013-005 delivers improved security, reliability, and compatibility by updating Java SE 6 to 1.6.0_65. On systems that have not already installed Java for OS X 2012-006, this... Read more
DEVONthink Pro 2.7 - Knowledge base, inf...
Save 10% with our exclusive coupon code: MACUPDATE10 DEVONthink Pro is your essential assistant for today's world, where almost everything is digital. From shopping receipts to important research... Read more
VirtualBox 4.3.0 - x86 virtualization so...
VirtualBox is a family of powerful x86 virtualization products for enterprise as well as home use. Not only is VirtualBox an extremely feature rich, high performance product for enterprise customers... Read more
Merlin 2.9.2 - Project management softwa...
Merlin is the only native network-based collaborative Project Management solution for Mac OS X. This version offers many features propelling Merlin to the top of Mac OS X professional project... Read more
Eye Candy 7.1.0.1191 - 30 professional P...
Eye Candy renders realistic effects that are difficult or impossible to achieve in Photoshop alone, such as Fire, Chrome, and the new Lightning. Effects like Animal Fur, Smoke, and Reptile Skin are... Read more
Sound Studio 4.6.6 - Robust audio record...
Sound Studio lets you easily record and professionally edit audio on your Mac.Easily rip vinyls and digitize cassette tapes or record lectures and voice memos. Prepare for live shows with live... Read more
DiskAid 6.4.2 - Use your iOS device as a...
DiskAid is the ultimate Transfer Tool for accessing the iPod, iPhone or iPad directly from the desktop. Access Data such as: Music, Video, Photos, Contacts, Notes, Call History, Text Messages (SMS... Read more

Ingress – Google’s Augmented-Reality Gam...
Ingress – Google’s Augmented-Reality Game to Make its Way to iOS Next Year Posted by Andrew Stevens on October 16th, 2013 [ permalink ] | Read more »
CSR Classics is Full of Ridiculously Pre...
CSR Classics is Full of Ridiculously Pretty Classic Automobiles Posted by Rob Rich on October 16th, 2013 [ permalink ] | Read more »
Costume Quest Review
Costume Quest Review By Blake Grundman on October 16th, 2013 Our Rating: :: SLIGHTLY SOURUniversal App - Designed for iPhone and iPad This bite sized snack lacks the staying power to appeal beyond the haunting season.   | Read more »
Artomaton – The AI Painter is an Artific...
Artomaton – The AI Painter is an Artificial Artistic Intelligence That Paints From Photos You’ve Taken Posted by Andrew Stevens on October 16th, 2013 [ | Read more »
Hills of Glory 3D Review
Hills of Glory 3D Review By Carter Dotson on October 16th, 2013 Our Rating: :: BREACHED DEFENSEUniversal App - Designed for iPhone and iPad Hills of Glory 3D is the most aggravating kind of game: one with good ideas but sloppy... | Read more »
FitStar: Tony Gonzalez Adds New 7 Minute...
FitStar: Tony Gonzalez Adds New 7 Minute Workout Program for Those Who Are in a Hurry Posted by Andrew Stevens on October 16th, 2013 [ permalink ] | Read more »
PUMATRAC Review
PUMATRAC Review By Angela LaFollette on October 16th, 2013 Our Rating: :: INSIGHTFULiPhone App - Designed for the iPhone, compatible with the iPad PUMATRAC not only provides runners with stats, it also motivates them with insights... | Read more »
Flipcase Turns the iPhone 5c Case into a...
Flipcase Turns the iPhone 5c Case into a Game of Connect Four Posted by Andrew Stevens on October 15th, 2013 [ permalink ] | Read more »
Halloween – Domo Jump Gets a Halloween T...
Halloween – Domo Jump Gets a Halloween Themed Level and New Costumes Posted by Andrew Stevens on October 15th, 2013 [ permalink ] | Read more »
Block Fortress War is Set to Bring a Mix...
Block Fortress War is Set to Bring a Mix of MOBA, RTS, and Block Building Gameplay To iOS This December Posted by Andrew Stevens on October 15th, 2013 [ | Read more »

Price Scanner via MacPrices.net

Updated MacBook Price Trackers
We’ve updated our MacBook Price Trackers with the latest information on prices, bundles, and availability on MacBook Airs, MacBook Pros, and the MacBook Pros with Retina Displays from Apple’s... Read more
13-inch Retina MacBook Pros on sale for up to...
B&H Photo has the 13″ 2.5GHz Retina MacBook Pro on sale for $1399 including free shipping. Their price is $100 off MSRP. They have the 13″ 2.6GHz Retina MacBook Pro on sale for $1580 which is $... Read more
AppleCare Protection Plans on sale for up to...
B&H Photo has 3-Year AppleCare Warranties on sale for up to $105 off MSRP including free shipping plus NY sales tax only: - Mac Laptops 15″ and Above: $244 $105 off MSRP - Mac Laptops 13″ and... Read more
Apple’s 64-bit A7 Processor: One Step Closer...
PC Pro’s Darien Graham-Smith reported that Canonical founder and Ubuntu Linux creator Mark Shuttleworth believes Apple intends to follow Ubuntu’s lead and merge its desktop and mobile operating... Read more
MacBook Pro First, Followed By iPad At The En...
French site Info MacG’s Florian Innocente says he has received availability dates and order of arrival for the next MacBook Pro and the iPad from the same contact who had warned hom of the arrival of... Read more
Chart: iPad Value Decline From NextWorth
With every announcement of a new Apple device, serial upgraders begin selling off their previous models – driving down the resale value. So, with the Oct. 22 Apple announcement date approaching,... Read more
SOASTA Survey: What App Do You Check First in...
SOASTA Inc., the leader in cloud and mobile testing announced the results of its recent survey showing which mobile apps are popular with smartphone owners in major American markets. SOASTA’s survey... Read more
Apple, Samsung Reportedly Both Developing 12-...
Digitimes’ Aaron Lee and Joseph Tsai report that Apple and Samsung Electronics are said to both be planning to release 12-inch tablets, and that Apple is currently cooperating with Quanta Computer on... Read more
Apple’s 2011 MacBook Pro Lineup Suffering Fro...
Appleinsider’s Shane Cole says that owners of early-2011 15-inch and 17-inch MacBook Pros are reporting issues with those models’ discrete AMD graphics processors, which in some cases results in the... Read more
Global Notebook Shipments To Grow Less Than 3...
Digitimes Research’s Joanne Chien reports that Taiwan’s notebook shipments grew only 2.5% sequentially, and dropped 8.6% year-over-year in the third quarter despite the fact that notebook ODMs have... Read more

Jobs Board

Senior Mac / *Apple* Systems Engineer - 318...
318 Inc, a top provider of Apple solutions is seeking a new Senior Apple Systems Engineer to be based out of our Santa Monica, California location. We are a Read more
*Apple* Retail - Manager - Apple Inc. (Unite...
Job Summary Keeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you’re a master of them all. In the store’s fast-paced, Read more
*Apple* Solutions Consultant - Apple (United...
**Job Summary** Apple Solutions Consultant (ASC) - Retail Representatives Apple Solutions Consultants are trained by Apple on selling Apple -branded products Read more
Associate *Apple* Solutions Consultant - Ap...
**Job Summary** The Associate ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The Associate ASC's role is to Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.