TweetFollow Us on Twitter

Finishing Our First Cocoa App

Volume Number: 20 (2004)
Issue Number: 4
Column Tag: Programming

Getting Started

by Dave Mark

Finishing Our First Cocoa App

In last month's column, I told you about my fabulous trip to Big Nerd Ranch for some down home Cocoa training with Aaron Hillegass and crew. We then started on our first in a series of Cocoa programs. We used Xcode to create a new project (named RandomApp), then used Interface Builder to edit the nib file and create the RandomApp user interface.

Figure 1 shows the final configuration of the window we laid out in Interface Builder. The top button is used to seed the random number generator. Press the second button to generate a new random number. The new number is displayed in the text field below the two buttons. In Figure 1, the text field is selected and the blue, dashed lines show the window was being resized to leave the proper amount of space below the text field and to the right of the two buttons and the text field.


Figure 1. The final window, showing two buttons and a text field.

Once the window was laid out to our satisfaction, we selected Test Interface from Interface Builder's File menu to take the interface for a test drive.

So what's next? Aha! Glad you asked...

What's Next

Unless you've been patiently waiting with both Xcode and Interface Builder running in the background, chances are good that you saved last month's efforts and have since quit both apps.

OK, let's get back to work.

Launch Xcode and open last month's Xcode project. I saved my copy in my Documents/Projects/ directory in a subdirectory named RandomApp. Find and launch RandomApp.xcode.

When the project window appears, open the triangle to the left of the NIB Files group to reveal the project's nib file, MainMenu.nib. Double click on the nib file to open it in Interface Builder.

Outlets and Actions

Your next task is to create a subclass of NSObject that we'll use to respond to clicks in the Seed Generator and Generate Random Number buttons. The class will also modify the text field to display the newly generated random number when the Generate Random Number button is pressed.

The methods we create to respond to the button clicks are called actions. We'll create a unique action that we'll associate with each button.

We'll also need an instance variable that points to the text field so we can change it from the method tied to the Generate Random Number button. This kind of object pointer is known as an outlet.

When you start a new program, you'll almost always be thinking in terms of actions and outlets. This might be a little fuzzy, but hopefully by the time you get RandomApp up and running, this will be a bit clearer.

Let's start by creating our new class. You'll do this in the main Interface Builder window. The folks at Big Nerd Ranch like to refer to this window as the "doc" window. Cool with me. The doc window is shown in Figure 2. Don't worry too much about what all the different icons mean. We'll explore them all in future columns.


Figure 2. Interface Builder's "doc window".

For now, click on the doc window's Classes tab. If you don't see NSObject in the leftmost pane (See Figure 3), scroll to the left using the scrollbar at the bottom of the doc window. Click on NSObject to select it. NSObject is the root class for all Cocoa classes. Note that all classes start with a capital letter. When you create your class, you'll follow this convention.


Figure 3. The NSObject class selected in the Classes tab of the doc window.

To create your NSObject subclass, select Subclass NSObject from Interface Builder's Classes menu. A new class will appear in the second pane. Change the name to Foo, then hit return to lock in the name change. The name Foo should appear immediately after FirstResponder in the second column.

Now let's add our outlet and actions to our new Foo class.

With the Foo class name selected in the second column of the doc window, select Show Info from the Tools menu to bring up the inspector window. As you can see in Figure 4, the inspector currently shows 0 outlets and 0 actions for the Foo class. We'll start off by adding an outlet.


Figure 4. The inspector, showing 0 outlets and 0 actions for the Foo class.

Remember, an outlet is an instance variable that is a pointer to an object. Instead of doing all the work in code, we're going to use the point-and-click power of Interface Builder to add the class, then add the outlet instance variable and action methods to the Foo class and, ultimately, to generate the source code files that implement the Foo class to the Xcode project. Once you get used to this process, you'll never want to create classes from scratch again. Incredibly powerful stuff.

To add an outlet to Foo, click on the Add button in the lower-right corner of the inspector window (Figure 4). Be sure that the Outlets tab is selected or you'll be adding an action instead. Once you click the Add button, a new outlet will appear. Name the outlet textField, then set the outlet's type to NSTextField using the popup menu in the second column. Basically, you've just told Interface Builder to add an instance variable to the Foo class with the name textField and the type NSTextField. You've used the interface to do this instead of typing the source by hand.


Figure 5. Set the outlet's type to NSTextField from the popup menu.

Now let's add a couple of actions. Click on the Actions tab and click the Add button. Name the new action seed:, being sure to include the trailing colon. The colon is actually part of an Objective C method name. Note that by convention, Objective C method names always start with a lower case letter (as opposed to class names which, as mentioned, start with an upper case letter).

Next, add a second method. Call it generate: (yup, remember the colon). When you are done, your inspector window should look like the one shown in Figure 6.

    If you find your inspector window getting out of sync, it might be because you have clicked on a different Interface Builder object. The inspector always reports on the currently selected object. Click on a window, the inspector shows the window's properties. If you do get lost, go back to the doc window, click on the Classes tab, scroll all the way to the left, then click on the NSObject class, then on the Foo subclass. The title of the inspector window should now be Foo Class Info. If the contents of the window do not match Figure 6, be sure to select Attributes from the popup menu at the top of the inspector window.


Figure 6. The inspector window showing my two actions.

Generate the Source Files

You've now laid out the pieces that make up your Foo class. You've got a pointer to an NSTextField, as well as a pair of methods you'll want called when the user clicks the Seed Generator or Generate Random Number buttons.

Your next step is to generate the source code that defines the Foo class and add that source code to your Xcode project. Fortunately, Interface Builder can do all this for you with one menu selection.

Make sure that the Foo class name is selected in the second column of the doc window. Now, select Create Files for Foo from the Classes menu. A sheet will appear (See Figure 7) that asks you where you'd like to save the files, what type of files to create, and to which target to add the files. Unless you've done some monkeying around, the defaults will probably be just fine. You'll save the files in your main project directory (mine is called RandomApp). You'll want to create both a Foo.h and a Foo.m file. Foo.h is the include file that contains your class declaration. Foo.m contains the actual class definition (the seed: and generate: source code, for example).

The target is the specific Xcode build you want these source files to be part of. Since we only have one target, this is an easy choice. Make sure the RandomApp checkbox is checked.


Figure 7. Saving the Foo class files.

Click the Choose button to add the source files to your project. Notice that two new source code file names appear in your Xcode project window in the Groups & Files pane. Typically, the two names will be appended to the list in the Other Sources group (See Figure 8). Feel free to drag them into another group or subgroup as you like.


Figure 8. The files Foo.h and Foo.m are added to the Groups & Files list.

Create and Connect a Foo Instance

Before we edit the source code, there's just one more task ahead of us. We need to create an instance of the Foo class, then connect the outlet and actions to the appropriate objects. This will become clearer in a moment.

Go back into Interface Builder.

In the doc window, click on the Foo class name in the second column. Select Instantiate Foo from the Classes menu. To see your new object, click on the Instances tab in the doc window.

As you can see in Figure 9, a new icon has appeared. In the doc window. Note the tiny explamation point in the lower left corner of the Foo icon. If you hover your cursor over the exclamation point, a tool-tip will appear saying "Unconnected outlet(s) (textField)." We've declared an outlet named textField but we haven't connected it to a text field. Let's fix that.


Figure 9. The Foo instance in the doc window. Note the message about Unconnected outlet(s).

Control-drag from the Foo instance to the text field below the two buttons in our application window. As you can see in Figure 10, when you start the control-drag, a little square will appear in the Foo icon, then a line will follow your cursor as you drag to the text field. Once the text field is highlighted with a surrounding rectangle, you can release the mouse button.

To complete the connection, click the Connect button in the lower-right corner of the inspector window.

The purpose of this connection is to fill the Foo object's textField instance variable with a pointer to the window's text field so we can modify the contents of the text field in our source code.


Figure 10. Control drag from Foo to the text field below our two buttons.

Our next step is to connect each of our two buttons to the appropriate method using the same technique.

Control-drag from the Generate Random Number button to the Foo instance. In the inspector window, you should see a list of Foo methods to choose from. Click on generate: and then click the Connect button (See Figure 11). You can also double-click on generate: instead.

If your inspector window gets out of sync, be sure that Connections is selected from the popup at the top of the window, then make sure that the Target/Action tab is selected. Finally, be sure that you dragged from the Seed Generator button to the Foo instance.

Next, let's connect the Seed Generator button to the seed: action. Control-click from the Seed Generator button to the Foo instance in the doc window. Next, select seed: and click the Connect button.


Figure 11. Click the Connect button to connect the Generate Random Number button to the generate: method.

That's it! Save your changes. This last step is very important as we are going to switch over to Xcode and we want to be sure we are dealing with the latest version of the .nib file.

Editing Your Source Code

In most programming projects, editing the source code is by far the biggest step to building your project. Because of the power of Interface Builder and the reusability of all the existing Cocoa objects, our source code changes will be pretty minimal.

Let's take a look at Foo.h.

Find Foo.h in the Groups & Files pane. Click on it. If the source code does not appear in an editing pane, select Show Embedded Editor from the View menu.

Here's the source code that Interface Builder placed in Foo.h:

/* Foo */
#import <Cocoa/Cocoa.h>
@interface Foo : NSObject
{
    IBOutlet NSTextField *textField;
}
- (IBAction)generate:(id)sender;
- (IBAction)seed:(id)sender;
@end

The #import statement is basically a #include that avoids the recursive effects of including a file that includes you.

The @interface statement declares the Foo class as a subclass of NSObject. There is a single instance variable, textField. Instance variables are declared inside the curly braces, Methods are declared after the curly braces and before the @end statement.

You don't need to change a line of this code. Interface Builder did all the work for you. Let's edit Foo.m, where the real action is. Here's what Foo.m looks like before you change it:

#import "Foo.h"
@implementation Foo
- (IBAction)generate:(id)sender
{
}
- (IBAction)seed:(id)sender
{
}
@end

Here's the edited version:

#import "Foo.h"
@implementation Foo
- (IBAction)generate:(id)sender
{
   int generated;
   
   generated = (random() % 100) + 1;
   
   [textField setIntValue:generated];
}
- (IBAction)seed:(id)sender
{
   srandom( time( NULL ) );
   [textField setStringValue:@"Generator seeded"];
}
- (void)awakeFromNib
{
   [textField setStringValue:@"Seed the Generator!!!"];
}
@end

Basically, you are adding 3 lines to the generate: method, 2 lines to the seed: method, and the 4 lines that make up the awakeFromNib: method. I added awakeFromNib: so the text field would have a reasonable setting at startup.

Don't worry too much about the code itself. The key here is that with 9 pretty simple lines of code and some time invested in Interface Builder, we've created a running application that does something interesting.

Build and run the application by selecting Build and Run from the Build menu. Figure 12 shows RandomApp when it starts up. Click the Seed Generator button, then click Generate Random Number to start generating random numbers. Hey, it works!


Figure 12. RandomApp in action.

Some Ramblings Before I Go

Some unrelated blathering before I leave. Sort of a static blog, if you will.

Deneen and I just got a Prius. To me, this is the car of the future. Today. I really, really love this car. It is a hybrid vehicle with a gas engine and an electric motor. The Prius switches between the two as needed. Gets extremely high gas mileage and has very low emissions. Worth checking out.

If you get a sec, go to http://www.spiderworks.com and check out my new project. It consumes me.

Also, I want to stand up on my chair and applaud O'Reilly for publishing Wil Wheaton's short story collection, Dancing Barefoot. I love that they did this. Wil Wheaton is an actor, played Wesley Crusher in a past life and, most importantly, has an exceptionally entertaining web site:

http://www.wilwheaton.net

Check out the site, check out the book.

Oh Yeah - WWDC is Just Around the Corner

Can you believe it? WWDC is just a couple of months away. Just like last year, this year's Worldwide Developers Conference will be in San Francisco from June 28th through July 2nd. Apple has reported that they have close to 10 million active Mac OS X users and over 10,000 native Mac OS X applications. These numbers show incredible adoption growth since last year's conference and that's good news for developers.

This year's conference offers 7 tracks: Application Technologies, Development Tools, Enterprise IT, Graphics and Media, Hardware Technologies, OS Foundations, and QuickTime Digital Media. Look for the QuickTime track to mix in integration of Pro Apps (DVD Studio Pro, for example) and to cover creation of audio loops for Soundtrack, GarageBand, Logic, etc. This one is definitely on my short list!

Read all about the conference here:

http://developer.apple.com/wwdc/features.html

Note that there is a discount if you buy your ticket by April 30th.

Till Next Month...

I am having a great time writing about Cocoa. Expect this nonsense to continue. If you insist on homework, find the Property List Editor (/Developer/Applications/Utilities/) and use it to open (a copy of) your .nib file. Fascinating.

See you in the future...


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
$102.99
Apple Inc.
+0.52
MSFT
$44.38
Microsoft Corpora
-0.50
GOOG
$532.71
Google Inc.
+6.17

MacTech Search:
Community Search:

Software Updates via MacUpdate

OmniOutliner 4.1.3 - Organize your ideas...
OmniOutliner is a flexible program for creating, collecting, and organizing information. Give your creativity a kick start by using an application that's actually designed to help you think. It's... Read more
BBEdit 11.0 - Powerful text and HTML edi...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more
Apple Security Update 2014-005 - For OS...
Apple Security Update is recommended for all users and improves the security of Mac OS X. For information on the security content of this update, please visit this website: http://support.apple.com/... Read more
EyeTV 3.6.6 - Watch and record TV on you...
EyeTV brings a rich TV experience to your Mac. Watch live TV on your Mac. Pause, rewind, and record whenever you want. EyeTV gives you powerful control over what you watch and how you watch it. Put... Read more
RapidWeaver 6.0 - Create template-based...
RapidWeaver is a next-generation Web design application to help you easily create professional-looking Web sites in minutes. No knowledge of complex code is required, RapidWeaver will take care of... Read more
NTFS 12.0.39 - Provides full read and wr...
Paragon NTFS breaks down the barriers between Windows and OS X. Paragon NTFS effectively solves the communication problems between the Mac system and NTFS, providing full read and write access to... Read more
RestoreMeNot 2.0.3 - Disable window rest...
RestoreMeNot provides a simple way to disable the window restoration for individual applications so that you can fine-tune this behavior to suit your needs. Please note that RestoreMeNot is designed... Read more
Command-C 1.1.5 - Clipboard sharing tool...
Command-C is a revolutionary app which makes easy to share your clipboard between iOS and OS X using your local WiFi network, even if the app is not currently opened. Copy anything (text, pictures,... Read more
Macgo Blu-ray Player 2.10.9.1750 - Blu-r...
Macgo Mac Blu-ray Player can bring you the most unforgettable Blu-ray experience on your Mac. Overview Macgo Mac Blu-ray Player can satisfy just about every need you could possibly have in a Blu-ray... Read more
Apple iOS 8.1 - The latest version of Ap...
The latest version of iOS can be downloaded through iTunes. Apple iOS 8 comes with big updates to apps you use every day, like Messages and Photos. A whole new way to share content with your family.... Read more

Latest Forum Discussions

See All

Fighting Fantasy: Caverns of the Snow Wi...
Fighting Fantasy: Caverns of the Snow Witch 1.0 Device: iOS Universal Category: Games Price: $5.99, Version: 1.0 (iTunes) Description: Travel to Northern Allansia’s perilous Icefinger Mountains to defeat the wicked Snow Witch in this... | Read more »
TinType by Hipstamatic (Photography)
TinType by Hipstamatic 1.0 Device: iOS iPhone Category: Photography Price: $.99, Version: 1.0 (iTunes) Description: Create hauntingly beautiful, soul capturing portraits with TinType by Hipstamatic. Inspired by daguerreotypes,... | Read more »
The Latest Update for Heroes of Dragon A...
The Latest Update for Heroes of Dragon Age Introduces Daily PvE Challenges Posted by Ellis Spice on October 22nd, 2014 [ permalink ] | Read more »
A New Trailer has Been Revealed for Epic...
A New Trailer has Been Revealed for Epic of Kings Posted by Jessica Fisher on October 22nd, 2014 [ permalink ] Dead Mage Inc. has released a new, action-packed trailer for the upcoming Epic of Kings. | Read more »
Find the Line Review
Find the Line Review By Campbell Bird on October 22nd, 2014 Our Rating: :: INSLIDE THE LINESUniversal App - Designed for iPhone and iPad Tease out beautiful line drawings in this unique, free-to-play puzzle game.   | Read more »
The Silent Age Episode 2 Review
The Silent Age Episode 2 Review By Jennifer Allen on October 22nd, 2014 Our Rating: :: ROUNDING THINGS OFF NICELYUniversal App - Designed for iPhone and iPad Rounding off a great point and click adventure comes The Silent Age... | Read more »
Craft Your Own Mini-Games with Papercade
Craft Your Own Mini-Games with Papercade Posted by Jessica Fisher on October 22nd, 2014 [ permalink ] iPad Only App - Designed for the iPad Scrapbookers move over, Scrapgaming is the new thing. | Read more »
Reshape Review
Reshape Review By Jennifer Allen on October 22nd, 2014 Our Rating: :: SIMPLE SHAPESUniversal App - Designed for iPhone and iPad Match triangles together to form cubes in this fast-paced and twitchy game.   | Read more »
Miika (Games)
Miika 1.0.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0.0 (iTunes) Description: Miika is a beautiful 3D puzzle game based on camera perspectives combined with the use of optical illusions. Miika challenges... | Read more »
Infuse Pro (Photography)
Infuse Pro 3.0 Device: iOS Universal Category: Photography Price: $9.99, Version: 3.0 (iTunes) Description: ** All-new version 3 includes fully licensed and certified DTS® and DTS-HD® audio! ** | Read more »

Price Scanner via MacPrices.net

Save with Best Buy’s College Student Deals
Take an additional $50 off all MacBooks and iMacs at Best Buy Online with their College Students Deals Savings, valid through November 1st. Anyone with a valid .EDU email address can take advantage... Read more
iPad Air 2 & iPad mini 3 Best Tablets Yet...
The new iPads turned out to be pretty much everything I’d been hoping for and more than I’d expected.”More” particularly in terms of a drinking-from-a-firehose choice of models and configurations,... Read more
Drafts 4 Reinvents iOS Productivity App
N Richland Hills, Texas based Agile Tortoise has announced the release of Drafts 4 for iPhone and iPad. Drafts is a quick capture note taking app with flexible output actions. Drafts 4 scales from... Read more
AT&T accepting preorders for new iPads fo...
AT&T Wireless is accepting preorders for the new iPad Air 2 and iPad mini 3, cellular models, for $100 off MSRP with a 2-year service agreement: - 16GB iPad Air 2 WiFi + Cellular: $529.99 - 64GB... Read more
Apple offering refurbished Mac Pros for up to...
The Apple Store is offering Apple Certified Refurbished 2013 Mac Pros for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The... Read more
Select MacBook Airs $100 off MSRP, free shipp...
B&H Photo has 2014 a couple of MacBook Airs on sale for $100 off MSRP. Shipping is free, and B&H charges NY sales tax only. They also include free copies of Parallels Desktop and LoJack for... Read more
13-inch 2.5GHz MacBook Pro on sale for $100 o...
B&H Photo has the 13″ 2.5GHz MacBook Pro on sale for $999.99 including free shipping plus NY sales tax only. Their price is $100 off MSRP. Read more
Strong iPhone, Mac And App Store Sales Drive...
Apple on Monday announced financial results for its fiscal 2014 fourth quarter ended September 27, 2014. The Company posted quarterly revenue of $42.1 billion and quarterly net profit of $8.5 billion... Read more
Apple Posts How-To For OS X Recovery
OS X 10.7 Lion and later include OS X Recovery. This feature includes all of the tools you need to reinstall OS X, repair your disk, and even restore from a Time Machine backup. OS X Recovery... Read more
Mac OS X Versions (Builds) Supported By Vario...
Apple Support has posted a handy resource explaining which Mac OS X versions (builds) originally shipped with or are available for your computer via retail discs, downloads, or Software Update. Apple... Read more

Jobs Board

Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, 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
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Position Opening at *Apple* - Apple (United...
…customers purchase our products, you're the one who helps them get more out of their new Apple technology. Your day in the Apple Store is filled with a range of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.