TweetFollow Us on Twitter

Getting Started with Cocoa...

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

Getting Started

by Dave Mark

Getting Started with Cocoa...

As anyone who knows me well can tell you, I love programming the Mac. And I'll play with just about anything out there that lets me build a Mac app or somehow control the Mac interface. When I first installed Mac OS X on my laptop, I immediately downloaded the developer tools, dug into the doc and started building Cocoa applications. And immediately got stuck.

Like a lot of other folks out there, I was a bit overwhelmed with all I needed to learn to truly understand the mechanics of Cocoa. For example, I know that I can use Interface Builder to lay out the user interface for an application. But why do I need to control-click-drag from one interface element to another? What are outlets? Actions? Targets? What the heck is a File's Owner or a First Responder?

These questions are the tip of the iceberg, but common to everyone when they first take on Cocoa. There are a number of Cocoa books out there, some of them quite good, but they all make some pretty big leaps in logic - not a big problem for professional developers, but those leaps can leave beginners scratching their heads, trying to decide if Cocoa is really hard to master or if they are just not up to the task. Let me assure you - Cocoa really is a challenge, even for the experienced developer.

Over the next few months, we're going to dig into Cocoa and get the basics down. Build up a deep enough understanding of Cocoa mechanics so that all those Cocoa books on your shelf make a lot more sense.

Big Nerd Ranch

Before we start, I wanted to digress for just a moment, talk about a great experience I just had. A few weeks ago, Scott Knaster and I were fortunate enough to head down to historic Banning Mills, about an hour southwest of Atlanta for a week of intensive Cocoa training with the folks at Big Nerd Ranch.

    Banning Mills is located on about 700 acres along the picturesque Snake Creek in Carroll County, Georgia. Originally home to the Creek and Cherokee nations, in the mid-1800s it became home to one of the earliest textile mills in the south. Over time, a masonry mill was built, the mill town grew, wool and cotton yarn was produced and processed into cloth. Paper and lumber products, meal, and flour were also produced. The area become an important part of the southern economy.

Towards the end of the Civil War, General William Tecumseh Sherman was sent to find the mills and destroy them. Because of the unique geography of the area (the mills are in an extremely well-hidden gorge), he was unable to locate the mills and they survived.

Check out http://historicbanningmills.com

I arrived at the ranch on Sunday evening, with the class scheduled to start Monday morning. Checked into my cabin - rustic with a standalone gas fireplace that really heated up the room - not so rustic with jacuzzi tub, phone, and TV with cable as well. Call it "charming with modern amenities". Once I unpacked, I headed over to the main lodge. To my surprise and delight, there was a nice spread of food laid out, complete with a drinks cooler (with all my favorites) and an ice cream freezer with about every kind of ice cream you could imagine. And, best of all, everyone in the class drifted in and we all sat around the dining table eating and getting to know one another. ScottK kept us all entertained with war stories from his days at Apple, General Magic, and Microsoft. Somehow, each story ended up with Scott making friends with a newly minted billionaire. Sadly, none of them was me.

The classes themselves were held in an upstairs meeting room at the lodge. Rustic, yet comfortable. A door off of the classroom led onto a large deck with a majestic view of Snake Creek and the surrounding rocky terrain. At night (and every night was a very late night) we'd go out onto the deck, talk Cocoa, and take in a sky full of stars. No light pollution at Big Nerd Ranch.

Our teacher, Aaron Hillegass, was exceptional. The class was based on an upcoming second edition of his book, Cocoa Programming for Mac OS X. The book was presented in loose-leaf format. The downside of working from a work-in-progress is that the code on disk frequently differed from the code on the pages. Sometimes the book was right, sometimes the disk was right. I typed in all the code and fixed any anomalies as I went along. Aaron was terrific about answering questions and helping debug our apps. I liked the fact that I typed in the code, as I was sure that I understood what ultimately ended up working.


Figure 1. The graduating class, from left to right: Rick Steele, Bryan Lockwood, Chris Campbell, Scott Knaster, Aaron Hillegass, Dave Mark, Allan Hoeltje, Jorge Ramirez, Mark Dalrymple, and Derek Chan. Aaron was the head cheese, and Chris and Mark his able assistants.

As far as content goes, we covered Objective-C in detail, spent some time on Xcode, Interface Builder and the Debugger, then got into Cocoa itself. Rather than go over the hierarchy class-by-class, Aaron presented overarching concepts, then introduced the classes in place as they occurred in the code. For example, he started by introducing a basic user interface with buttons and a text field, then introduced classes like NSControl (and subclasses NSButton, NSSlider, NSTextField) and NSAppController. Rather than tour through each class, Aaron started in Interface Builder and wired the app together, giving an overview of each class as it was hooked in place. This gave us less of an exhaustive view of the class hierarchy and much more a sense of the Cocoa design philosophy. An excellent approach.

We explored Helper Objects, Bindings and NSController (and the very important Key-value Coding concept), NSUndoManager (holy cow - it really is easy to add undo to your app!), Archiving and the Document Architecture, Nib files and NSWindowController, User Defaults, Notiffications, Alert Panels, Localization, Custom Views, Events, Responders, Fonts, Pasteboards, Categories, Drag-and-Drop, NSTimer, Sheets, NSFormatters, Printing, Menus, NSTextView, building your own Interface Builder palettes, AppleScript, and OpenGL.

An amazing amount of material, crammed into way too little time. Yet somehow it all worked. I came away remembering much of what was taught, but more importantly, I had enough resource material to recreate anything I'd forgotten.

If you can afford it, I would strongly recommend Big Nerd Ranch. Come prepared, though, as the pace is intense. At the very least, before you head out, I would read the document ObjC.pdf in this directory:

/Developer/Documentation/Cocoa/Conceptual/ObjectiveC/

Do your homework first, and I know you will find the experience to be tremendously rewarding. Check out the Big Nerd Ranch website at http://www.bignerdranch.com. You can call them at (678) 595-6773.

The Number Generator

Perhaps the best way to get started with Cocoa is with a simple application that makes use of both Interface Builder and Xcode, just so you can get a feel for the development process. Don't worry about the concepts. Just click and drag and follow along. Over time, the steps you take in this program will become second nature.

This is the very first project in the upcoming second edition of Aaron Hillegass' Cocoa Programming for Mac OS X. The book should hit the streets in a few months.

The program, called RandomApp, puts up a window with a couple of buttons and a text field. One button initializes the system's random number generator and the second button asks the generator to generate a random number between 1 and 100. The number is displayed in the text field. The result is shown in Figure 2.


Figure 2. RandomApp in action.

In this month's installment, we'll create a project in Xcode, then use Interface Builder to build and test the interface. Next month, we'll add the wiring to tie the buttons to the appropriate code, then add the code itself. Sounds good? Let's get started...

Create a New Xcode Project

Launch Xcode and select New Project... from the File menu. When prompted, select Cocoa Application as the project type (see Figure 3). Cocoa Application is under the Application section. Be sure you do not select Cocoa Document-based Application. Click the Next button.

Be sure you have the latest and greatest version of the developer tools installed. I wrote this column using Xcode version 1.1. You can download the tools at http://developer.apple.com. You'll need to join Apple Developer Connection but it is free to join.


Figure 3. Build a new Cocoa Application project.

Next, you'll be prompted to enter a project name and project directory (see Figure 4). Name the project RandomApp and save it in an appropriate directory. Click the Finish button.


Figure 4. Name the project RandomApp and save it in an appropriate directory.

Your project window will appear and Xcode will immediately begin indexing the project files. This happens in the background and is the reason Xcode's searches are so incredibly quick.

The left pane of the project window lists the Groups & Files that make up the project. One of these groups is named NIB Files. Open the NIB Files triangle and you will find the nib file for this project, named MainMenu.nib (see Figure 5). Double-click on MainMenu.nib to open the nib file in Interface Builder.


Figure 5. The RandomApp project window, with MainMenu.nib selected.

Laying Out the User Interface

Interface Builder is an incredibly powerful tool. It not only allows you to design your application's user interface, it also let's you define the interactions between the objects that make up your application. Mastering the intricacies of connecting objects will take time. We will definitely spend a lot of time experimenting over the months ahead. For now, just follow along and get RandomApp up and running. You'll get a basic sense of the interaction between Interface Builder and Xcode, and you'll feel a bit more comfortable knowing all your tools are in place and working properly.

When Interface Builder appears, you should see a menu window labeled MainMenu.nib - MainMenu, a window labeled Window, a main window labeled MainMenu.nib, and a floating palette whose name changes depending on the icon selected from the row at the top of the palette. In the palette window, click on the icon with a button and a slider (2nd from the left, as shown in Figure 6) to bring up the controls palette.


Figure 6. Interface Builder's controls palette

Click on the button in the upper-left corner and drag it onto the window labeled Window. Take a look at Figure 7. Notice that as the button neared Window's upper-left corner, A pair of blue dashed lines appeared. These guide lines tell you the item you are dragging is an appropriate distance from the nearest other interface element (in this case, the top and the side of the window). This is quite a handy way of lining up your interface objects.


Figure 7. Dragging a button from the palette onto the window.

Next, click to select the button, then click on the right resize bits and drag the rectangle to the right, till the blue dashed line towards the right end of the window appear. Now you should have a button that is almost as wide as the window.

Double-click on the word Button and type Seed Generator, followed by a return. The button text should change appropriately.

Now drag out a second button underneath the first one. This time, there will be blue guidelines above and to the left of the button as you drag it out. These guides will keep the button the proper distance from the top button and the left side of the window.

Drag the right side of the button to make it as wide as the top button. Double-click on the word button and change its text to say Generate Random Number.

Figure 8 shows what we have so far...


Figure 8. Our window with two buttons.

Our next step is to drag out a static text field onto the window. In the palette window, click on the 3rd icon in the top row (the one that looks like a scrolling text field). The palette title should change to read Cocoa - Text and a series of text related objects should appear in the palette window.

Click and drag a static text item from the lower right corner of the palette onto the window we are building. Notice that you have a choice of several different size static text items. The one we want is the largest one and is labeled System Font Text. Just as you did with the buttons, drag the text to the left side of the window, underneath the 2nd button. Use the blue guide lines to make sure your spacing is right.

Click and drag on the right side of the text field to resize it to the same width as the buttons.

Next, select Show Info from the Tools menu to bring up a floating inspector window. When the Info window appears, click on the static text field you just created. The fields of the Info window will change to reflect the settings of the static text field. Change the Title field to the number 0 and click on the centering icon in the Alignment: field. Figure 9 shows my settings.


Figure 9. The info window, showing the changes we've made to the NSTextField.

Finally, click and drag the window to make it shorter. Keep it the same width, though. Figure 10 shows my final window.


Figure 10. The final window.

Test Drive the Interface

Now that your interface is finished, let's take it for a spin. Select Test Interface from the File menu. The RandomApp window should appear, with the title Window and the buttons and text as we've laid them out.

The buttons should be operable, though they won't actually do anything. When you are done playing, select Quit NewApplication from the Interface Builder menu. This will quit the test drive, not Interface Builder itself.

Till Next Month...

In next month's column, we'll use Interface Builder to create a new class specifically designed to seed the random number generator and generate a new random number. We'll create an instance of the class and wire the two buttons to the instance's methods that seed the generator and generate a new number. We'll then go into Xcode and add the code to make the application complete.

If you dare, take some time to play with Interface Builder and customize your interface. Change the window's title from Window to RandomApp. Change the menus. And if you double-dare, try your hand at finishing the program yourself.

Before you start mucking, thought, please save your changes and make a copy of your project directory. Next month, we'll want to start exactly where we left off. See you then! J


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. Interested in Learning Cocoa? Be sure to check out Dave's web site at http://www.spiderworks.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

OmniOutliner Pro 5.4.1 - Pro version of...
OmniOutliner Pro 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
EarthDesk 7.3 - $24.99
EarthDesk replaces your static desktop picture with a rendered image of Earth showing correct sun, moon, and city illumination. With an Internet connection, EarthDesk displays near-real-time global... Read more
Monosnap 3.5.3 - Versatile screenshot ut...
Monosnap lets you capture screenshots, share files, and record video and .gifs! Features Capture Capture full screen, just part of the screen, or a selected window Make your crop area pixel... Read more
Monosnap 3.5.3 - Versatile screenshot ut...
Monosnap lets you capture screenshots, share files, and record video and .gifs! Features Capture Capture full screen, just part of the screen, or a selected window Make your crop area pixel... Read more
Spotify 1.0.93.244 - Stream music, creat...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
Evernote 7.6 - Create searchable notes a...
Evernote allows you to easily capture information in any environment using whatever device or platform you find most convenient, and makes this information accessible and searchable at anytime, from... Read more
Final Cut Pro X 10.4.4 - Professional vi...
Final Cut Pro X is a professional video editing solution. Completely redesigned from the ground up, Final Cut Pro adds extraordinary speed, quality, and flexibility to every part of the post-... Read more
Compressor 4.4.2 - Adds power and flexib...
Compressor adds power and flexibility to Final Cut Pro X export. Customize output settings, work faster with distributed encoding, and tap into a comprehensive set of delivery features. Features... Read more
Motion 5.4.2 - Create and customize Fina...
Motion is designed for video editors, Motion 5 lets you customize Final Cut Pro titles, transitions, and effects. Or create your own dazzling animations in 2D or 3D space, with real-time feedback as... Read more
Thunderbird 60.3.1 - Email client from M...
As of July 2012, Thunderbird has transitioned to a new governance model, with new features being developed by the broader free software and open source community, and security fixes and improvements... Read more

Latest Forum Discussions

See All

Slots Panther Vegas offers a social gamb...
New era of Online gambling Want to try your luck in online social gambling? More and more people are into online casinos as a risk-free amazing way to experience the excitement of a big game. Online casinos and slots machines are gaining popularity... | Read more »
3 features we think you'll love in...
Well known classic RPG “Shin Megami Tensei” franchise originally created by Atlus, can now be played throughout iOS and Android. Created by Sega, “Shin Megami Tensei” has spawned a mobile-centric installment in the shape of “Shin Megami Tensei:... | Read more »
These are the top 3 games for iPhone and...
The end of the week has rolled around again, which means it's time for us to look forward to the games you're going to be playing over the next seven days. We've got the return of a mobile gaming legend next week, as well as a couple of other... | Read more »
Time for you to pick which of these top...
Oh look, Thursday is upon us once more. And we all know what that means! You guessed it, it's time for you to vote for which of these five games you think deserves to win our game of the week award. And have we got a selection for y'all this week... | Read more »
Dragalia Lost - High Midgardsormr Prep G...
It might not seem like there's a ton to do between events in Dragalia Lost, but there is one high level piece of content that can keep you occupied for a long time. Defeating High Midgardsormr is currently the game's most difficult non-event... | Read more »
Get your friends, these are the top 5 be...
You can't be a lone wolf all the time, especially if you want to show off your gaming prowess. And that's where this list comes in - we're running down what we think are the top 5 multiplayer games for iPhone. There might be some controversial... | Read more »
SpitKiss is the worthy winner of last we...
It's been a rough and tumble battle this week, with all of the games managing to get a few hits in where it counts, but after checking with the independent adjudicators at ringside, we can now reveal that gloriously gross smooching sim SpitKiss has... | Read more »
The best games for iPhone - The definiti...
Hi there, and welcome to our ever-increasing list of the very best games for iPhone. We're going to be updating this regularly with new content, so make sure you check back often, because you're not going to want to miss out on even one of the... | Read more »
Dragalia Lost Guide - What You Need To K...
Another raid has come and gone in Dragalia Lost, but that doesn’t mean there’s not still lots to do. In fact, the game’s next event, A Wish to the Winds, has already been announced and will be coming to the game this Wednesday. Although details are... | Read more »
The top 5 best games like Star Wars: Gal...
One of the things we like to do here at 148Apps is broaden your horizons. Maybe you're a fan of Star Wars: Galaxy of Heroes and you're looking for something that's going to scratch similar itches? Well that's where we come, and more specifically... | Read more »

Price Scanner via MacPrices.net

Save on a new MacBook with these early Black...
B&H Photo has posted early Black Friday sale prices on Apple MacBooks, including up to $300 off MSRP on 15″ MacBook Pros, $100 off new 13″ MacBook Airs, and more. Most of these deals expire... Read more
T-Mobile Black Friday deal: Free iPhone Xr wi...
T-Mobile is offering the 64GB iPhone Xr for free as part of their Black Friday 2018 sale. Two new lines are required, as well as an eligible trade-in (iPhone 6s models or newer). $20.84 is applied to... Read more
Save up to $157 on a 10.5″ iPad Pro with thes...
Apple’s newest authorized reseller, Jet, has 10.5″ iPad Pros on sale for up to $157 off MSRP as part of their Black Friday week sale. Shipping is free. Note that some sale prices may be restricted to... Read more
US Cellular offers free iPhone Xr for new lin...
US Cellular is offering the 64GB iPhone Xr for free as part of their Black Friday 2018 sale. A new line is required, but there is no trade in requirement. Any of the iPhone Xr colors qualify. The... Read more
Roundup of Black Friday Week 2018 Sales &...
At MacPrices.net, we give you the most accurate Mac and Apple prices on the web. Choose one of our price trackers at the top of the page to see all the current sale prices on Apple’s products from... Read more
Details of Amazon’s 2018 Black Friday week di...
Amazon’s recent agreement with Apple has allowed the online store to add most of Apple’s most popular products to its inventory, including new 2018 iPad Pros, Mac minis, Apple Watch Series 4, and... Read more
Get A Job With Apple, The No. 3 ‘World’s Best...
FEATURE: 11.16.18- If you are a fan of Apple, Inc. and an avid user of any one of its vast array of tech gadgets, why not take it a step further and work for the company behind those products you... Read more
Sprint offers $100 discounts on Apple Watch S...
Sprint is offering customers $100 discounts on the purchase of a cellular Apple Watch Series 4 or Apple Watch Series 3. Their discount reduces the cost of a Series 4 watch to $399 (40mm) or $429 (... Read more
New 2018 11″ 64GB & 256GB iPad Pros in st...
MacMall has the new 2018 11″ 64GB and 256GB iPad Pros in stock today for $50 off Apple’s prices. They’re currently the lowest prices available for these new iPad Pros. – 11″ 64GB Space Gray WiFi iPad... Read more
New Mac minis in stock and available today at...
Apple Authorized Reseller Adorama has the new 2018 Mac minis in stock today today sales tax free for residents outside of NY & NJ. Shipping is also free. – 3.6GHz Quad-Core mini: $799 – 3.0GHz 6... Read more

Jobs Board

Best Buy *Apple* Computing Master - Best Bu...
**658102BR** **Job Title:** Best Buy Apple Computing Master **Job Category:** Sales **Location Number:** 000395-Pensacola-Store **Job Description:** **What does a Read more
*Apple* Mobile Master - Best Buy (United Sta...
**658022BR** **Job Title:** Apple Mobile Master **Job Category:** Store Associates **Location Number:** 000793-Dothan-Store **Job Description:** **What does a Best Read more
Geek Squad *Apple* Master Consultation Agen...
**657784BR** **Job Title:** Geek Squad Apple Master Consultation Agent **Job Category:** Services/Installation/Repair **Location Number:** 000597-Erie-Store **Job Read more
Best Buy *Apple* Computing Master - Best Bu...
**655276BR** **Job Title:** Best Buy Apple Computing Master **Job Category:** Sales **Location Number:** 000387-Randall Road-Store **Job Description:** **What does a Read more
Omni-Channel Associate - *Apple* Blossom Ma...
Omni-Channel Associate - Apple Blossom Mall Location:Winchester, VA, United States- Apple Blossom Mall 1850 Apple Blossom Dr Job ID:1074107 Date:November 12, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.