Tải bản đầy đủ (.pdf) (409 trang)

learn cocoa on the mac 2nd edition

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (19.22 MB, 409 trang )

www.it-ebooks.info
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
www.it-ebooks.info

v
Contents at a Glance
Preface ����������������������������������������������������������������������������������������������������������������������������� xvii
About the Authors �������������������������������������������������������������������������������������������������������������� xix
About the Technical Reviewer ������������������������������������������������������������������������������������������� xxi
Acknowledgments ����������������������������������������������������������������������������������������������������������� xxiii
Chapter 1: Must Love Cocoa ■ ����������������������������������������������������������������������������������������������1
Chapter 2: Hello, World ■ ������������������������������������������������������������������������������������������������������5
Chapter 3: Lights, Camera … Actions! (and Outlets, too) ■ �������������������������������������������������27
Chapter 4: The First Call to Action ■ �����������������������������������������������������������������������������������47
Chapter 5: GUI Components ■ ���������������������������������������������������������������������������������������������67
Chapter 6: Using Table Views ■ ����������������������������������������������������������������������������������������103
Chapter 7: Cocoa Bindings ■ ��������������������������������������������������������������������������������������������125
Chapter 8: Core Data Basics ■ ������������������������������������������������������������������������������������������153
Chapter 9: Core Data Relationships ■ �������������������������������������������������������������������������������189
Chapter 10: Search and Retrieve Core Data with Criteria ■ ���������������������������������������������209
Chapter 11: Windows and Menus and Sheets ■ ���������������������������������������������������������������225
Chapter 12: Document-Based Applications ■ �������������������������������������������������������������������253
www.it-ebooks.info

vi Contents at a Glance
Chapter 13: Exceptions, Signals, Errors, and Debugging ■ ����������������������������������������������271
Chapter 14: Drawing in Cocoa ■ ���������������������������������������������������������������������������������������295
Chapter 15: Advanced Drawing Topics ■ ��������������������������������������������������������������������������315
Chapter 16: Working with Files ■ �������������������������������������������������������������������������������������341


Chapter 17: Concurrency ■ �����������������������������������������������������������������������������������������������357
Chapter 18: Future Paths ■ �����������������������������������������������������������������������������������������������375
Index ���������������������������������������������������������������������������������������������������������������������������������389
www.it-ebooks.info
1

Chapter 1
Must Love Cocoa
Welcome! You must be here because you want to write programs for your Mac. Well, you’ve
definitely come to the right place. (Here for Pilates? Third door down, on the right.) By the time you
finish this book, you’ll know everything you need to know to create fast, efficient, good-looking
Mac OS X applications.
The key to creating a modern Mac application is Cocoa. According to Apple, Cocoa is a set of
object-oriented frameworks that provide a runtime environment for Mac OS X applications. As
you make your way through this book, you’ll learn all about the Cocoa frameworks and runtime
environment. For the moment, think of Cocoa as a programmer’s assistant that takes care of much
of the housekeeping that goes along with Mac development. Almost every common task performed
by a Mac application, from drawing a window to blinking the cursor in a text field, is handled for you
when you write programs using Cocoa, freeing you up to concentrate on the code that makes your
application unique.
Cocoa provides a class for just about every one of your development needs. There are Cocoa
classes for each piece of the Mac OS X user interface, from windows to menus, scrollbars to
buttons, images to icons. If you can think of a user interface element you’d like to add to your own
application, chances are very good that element is already implemented as a Cocoa class.
Another benefit of using Cocoa is that it is tightly integrated with Mac OS X. Build your application
using Cocoa, and your application will play well with others and will interface seamlessly with Mac
OS X elements like the Finder and the Dock.
WHEN IS 25 YEARS NOT 25 YEARS?

Cocoa has been around in one form or another since 1986. The technologies that we call Cocoa evolved from the

NeXTStep AppKit, the application building tools developed for the NeXT platform. When Apple bought NeXT in 1996, they
began building a new version of the Mac OS, what we now know as OS X, basing much of the new operating system on
technologies acquired from NeXT.
www.it-ebooks.info

2 CHAPTER 1: Must Love Cocoa
As OS X evolved, so did Cocoa. Apple added technologies from the classic Mac OS, like QuickTime, as well as completely
new technologies, like the Quartz rendering system that enables all the fancy visual effects and animation that OS X uses.
They also made sure that they kept the Mac’s famed ease-of-use in the process.
Bottom line: Cocoa is constantly evolving and expanding. The development tools, libraries, and frameworks you’ll be
learning in this book are the result of more than 25 years of experimentation and refinement.
Get a Mac and Download the Tools
Before you can begin creating applications with Cocoa, you’ll need a Mac. It doesn’t have to be the
newest or the most powerful Mac; in fact, pretty much any Mac that’s been made in the last four or
five years or so will work just fine for building the exercises in this book. As you become more serious
about writing software, you may find it’s worth investing in a newer or faster machine, but for now
just about any Intel-based Mac will work fine for learning what you need to learn. The latest Macs are
currently up to OS X 10.8, while the oldest Intel-based Macs can’t run any version of OS X later than
10.7. But Xcode 4.6, the version we’ll be using for this book, works fine on both 10.7 and 10.8.
You’ll also need to have an Apple ID (the same as you might already be using for the Mac or iOS App
Stores, or other iTunes purchases), and you should strongly consider joining the Apple Developer
Connection (ADC), which is Apple’s developer relations organization. There are paid memberships,
but the basic membership is free. To join ADC, open up your web browser and navigate to
If you already have an Apple ID, press the Log in button and
enter your info. If you are new to Apple’s online services, click the register link and create your
account.
Whether you sign up as a developer or just use your Apple ID, the easiest and best way to get
Xcode, Apple’s set of free developer tools, is to download it from the App Store on your Mac. Just
launch the App Store, search for Xcode, and tell it to install. As with most of what’s on the App Store,
installation is pretty much self-explanatory. Xcode’s installation may take quite a bit longer than most

other apps since it’s a pretty big download.
Note If you’ve already installed Xcode for doing iOS development, then you’re all set. Xcode contains all
the tools and frameworks needed for creating both OS X apps and iOS apps. Though the frameworks do have
major differences, the tools are pretty much the same, so if you’ve done any iOS development, you should feel
right at home creating Cocoa programs.
Download the Source Code
In addition to downloading and installing Xcode, you’ll also need to download the sample projects
that go with this book. You can find the code archive on the Apress Learn Cocoa on the Mac web
page at www.apress.com/9781430245421. This page contains all the metadata about this book,
including the code archive, errata, and more.
www.it-ebooks.info

3CHAPTER 1: Must Love Cocoa
Getting Help
As you make your way through the book, you’ll no doubt have some questions you’d like to get
answered. Fortunately, there is a great community you can join, designed specifically for this series
of books. Check out . Register with the site, find the appropriate book forum
and post your questions. You are sure to find other folks who can answer your questions and,
who knows, after a while you might find yourself answering questions for other folks as well. The
learncocoa.org site is also where you’ll find some info about other resources to help you on your
way, including other books, workshops, and more. Come join us!
What You Need to Know Before You Begin
This book assumes that you already have some basic programming knowledge. You should be
comfortable with the concepts of loops, variables, pointers, and linked lists. This book also assumes
that you understand the fundamentals of object-oriented programming and are familiar with the
Objective-C programming language. Starting with Mac OS X Leopard 10.5, a new version of the
language was introduced, called Objective-C 2.0. Don’t worry if you’re not familiar with the more
recent additions to the Objective-C language. We’ll be sure to highlight any of the 2.0 language
features we take advantage of and explain how they work and why we are using them.
NEW TO OBJECTIVE-C?


Here are a few resources that will help you get started.
New to programming? Check out Learn C on the Mac, 4th Edition, written by our good friend Dave Mark
(www.apress.com/9781430218098).
New to Objective-C? Check out Learn Objective-C on the Mac, 2nd Edition, an excellent and approachable introduction
to Objective-C by Mac programming experts Scott Knaster, Waqar Malik, and Mark Dalrymple
(www.apress.com/9781430241881).
Next, navigate over to Apple’s Mac Developer Library and download a copy of Programming with Objective-C, a very
detailed and extensive description of the language and a great reference guide ( />library/mac/#documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC).
Are You Ready?
The Mac is a great computing platform, and Cocoa is the best tool to use to build your Mac
applications. If you are coming to the Mac from another platform, you may find working with Cocoa
and Objective-C a bit disorienting. Even though you might find it hard to get your bearings at first,
as you make your way through this book, we’re confident that you’ll soon start to wrap your head
around the “Cocoa way” of doing things. With a little perseverance, it will all start to make sense.
www.it-ebooks.info

4 CHAPTER 1: Must Love Cocoa
One thing you should keep in mind is that the exercises in this book are not simply a checklist that,
when completed, grant you Cocoa developer guru status. Every step of the way, make sure you
understand what you just did before moving on to the next project. Don’t be afraid to make changes
to the code. Experiment and observe the results. That’s one of the best ways to understand the
complexities of coding in an environment like Cocoa.
Also, remember that we’ve set up a message forum for readers to discuss the exercises and content
of this book. So if you get stuck, or want to chat with us and other Cocoa developers about any Cocoa
programming topics, head over to and register for the discussion forum.
That said, if you’ve got Xcode installed, turn the page. If not, get to it! Then let’s go!
www.it-ebooks.info
5


Chapter 2
Hello, World
As you’re probably well aware, it has become something of a tradition to call the first project in any
book on programming “Hello, World.” Following the “if it ain’t broke, don’t fix it” guideline, we’ll stick
with tradition.
Building “Hello, World”
By now, you should have Xcode installed on your machine. You should also have the Learn Cocoa
Projects folder ensconced safely somewhere on your hard drive. If by some set of circumstances
you don’t, go directly to Chapter 1 (do not pass Go, do not collect $200) and reread the appropriate
sections.
The first project we’ll be working with is located in the Chapter02/Chapter2 folder. Launch Xcode,
which is located in the Applications folder. Just in case you’ve never used Xcode before, we’re
going to walk you through the process of creating a new project.
Start by selecting New Project from the File menu, or by typing ⇧⌘N. When the New Project
Assistant comes up (Figure 2-1), select Application from under the Mac OS X heading in the left
column, then select the Cocoa Application icon from the upper-right pane and click Next.
www.it-ebooks.info

6 CHAPTER 2: Hello, World
A Project Options window offers a number of choices (Figure 2-2). We need to specify a name for
our application. “Chapter2” is a good choice. We also need to give a company identifier, which
is formatted like a reversed domain name (much like a Java package name or C# namespace). If
we live at the megacorp.com domain name, then com.megacorp would be our choice here. Mac
OS X uses the combination of the product name and the company identifier as a unique name
for our program across the system, as well as in the Mac App Store. However, since we won’t be
distributing this app beyond our computer, we can pick anything we like. The last important field
here is the class prefix. As we’ll see, many of the Cocoa classes start with the prefix NS or CF. In
those classes, Xcode will generate some files for us as part of creating a new project, and it will use
the prefix we give here. For now, enter “Book.” We won’t be using the other fields in this chapter, so
they can be left at the default values. Click Next.

Figure 2-1. Selecting the Cocoa Application project template from Xcode’s New Project Assistant
www.it-ebooks.info

7CHAPTER 2: Hello, World
We’ll be presented with the standard Save window to set the location for our project (Figure 2-3).
Xcode will create a new folder with the name of our project in the location we pick: our Documents
folder or a newly-created separate folder to hold the Xcode projects that we build ourselves. It really
doesn’t matter where we save an Xcode project, but it’ll be easier to find them later if we always
save our projects in one place. We also have the choice to have Xcode configure our project for
version control using Git, a powerful open-source distributed version control system. For right now,
we can also leave this at the default setting.
Figure 2-2. Specifying options for a new Cocoa application from Xcode’s New Project Assistant
www.it-ebooks.info
8 CHAPTER 2: Hello, World
Once we select a location, a new project window will appear (as shown in Figure 2-4). Although you
might already be familiar with Xcode, take a second to look at the project window. This is where we
will be spending an awful lot of our time, so let’s make sure we’re all on the same page. Like many
applications built for Mac OS X 10.7 Lion and newer, Xcode includes a full-screen option. Since
Xcode is a complex application, it works best with a lot of screen real estate, and we should make it
full-screen now by clicking the arrows in the upper right-hand corner of the window.
Figure 2-3. Naming our project and selecting the save location
www.it-ebooks.info

9CHAPTER 2: Hello, World
Our project window features a toolbar across the top, which gives us ready access to a bunch of
commonly used commands. Below the toolbar, the window is divided into three main sections, or panes.
The pane that runs down the left side of the window is called the Navigator area. All of the resources
that make up our project are grouped here, as are a number of relevant project settings. Clicking the
little triangle to the left of an item expands that item to show any available subitems. Clicking the
triangle to the left of an expanded item will hide its subitems.

The right pane is called the Utility area, and it shows detailed information about items selected in the
Navigator area. For a source code file, for example, this area shows identity and type information,
the full path to the file in the file system, localization information, plus the build targets that use the
selected file, encoding information, and version control info. Other files show information appropriate
to the file type. Depending on the type of file selected in the Navigator pane, there may be a row of
small icons atop this area that allow us to select several different views of information to be shown
here. Below the information pane is the Library. We’ll be exploring more here in a moment.
The center pane is called the Editor pane. If we select a file in the Navigator pane, and Xcode knows
how to display or edit that kind of file, the contents of the file will be displayed in the Editor pane.
This is where we will be writing and editing all of the application’s source code.
Figure 2-4. Our project’s main window in Xcode
Note Many developers like to get rid of the Utility area when they are working in the Editor in order to
have more screen space devoted to editing code; we can toggle the Utility area by pressing ⌥⌘0.
www.it-ebooks.info

10 CHAPTER 2: Hello, World
Let’s now look at the Project Navigator area on the left side of the Xcode window. There are a
number of folders and three files that were created automatically for us. We’ll ignore the folders and
the first two files for the moment (we’ll revisit them later). The third file is named MainMenu.xib.
Click MainMenu.xib. The Editor pane will change to Interface Builder mode, the editor specifically
designed to edit .xib files (Figure 2-5). Prior to Xcode 4, Interface Builder was a separate application,
but it’s been merged into Xcode, and this brings a lot of benefits in wiring up the user interface to the
underlying code. The file MainMenu.xib is known as a “nib file.” Huh? A nib file? Why not a xib file?
Well, for starters, “xib” is awfully hard to pronounce. But more importantly, the term “nib” is a holdover
from an earlier, simpler time. The precursors to Cocoa and the modern Xcode development tools were
developed by NeXT, Inc., a company started by Steve Jobs in 1985. The name “nib” originally stood
for NeXT Interface Builder. Over time, NeXT was acquired by Apple, and the nib format evolved into
a newer, XML-based format. This combination of XML and Interface Builder yielded the new .xib
extension. Nonetheless, the name “nib file” stuck, and most developers still call their xib files “nib files.”
Figure 2-5. MainMenu.xib ready for editing

Warning You’ll find the file MainMenu.xib in every Cocoa project you create in Xcode. This is a
special file. Treat it as such. Do not move, rename, or otherwise annoy the file. Unless we tell you to.
When your application gets launched, it will automatically load the contents of MainMenu.xib into
memory. MainMenu.xib contains critical information, including your application’s menu bar and main
window (if it has one). Over time, you’ll learn all there is to know about nib files and will be rolling your
very own. For the moment, patience—and hands off.
www.it-ebooks.info

11CHAPTER 2: Hello, World
Exploring the Nib File
Interface Builder mode offers a lot of power, so let’s take a moment to see how things are laid
out. The Interface Builder Editor area looks like a piece of graph paper, with the menu bar of our
application across the top (Figure 2-5). Along the left, off the edge of the graph paper are a series
of icons in a dock. These are the objects that make up our Cocoa application’s user interface. Near
the bottom is a Play button that expands the dock into an outline mode where we can get more info
about these objects.
Note that the row of icons across the top of the Utility area, along the right side of the Xcode
window, has expanded from two to eight; these objects are more configurable than files are. Each of
these icons represents a different mode for the Inspector. We’ll have more to say about the different
types of information on display here shortly. Underneath this is the Library, with a row of four small
icons that shift the view to different types of items. Hovering our mouse over each icon will display
a tooltip describing the kind of items that each view shows. The Inspector is used to set parameters
on the objects that make up our user interface, and the Library is where we’ll go to add new objects
to lay out the interface.
The menu bar across the top of the Editor is for our application, and changes here will be reflected
in the menu bar that appears when our application is launched. We can click the menu headings,
and they’ll open up to show the menu items underneath; we get the Mac-standard File, Edit, Format,
View, Window, and Help menus for free with the new nib file, but we can add more and modify the
defaults if necessary. The icon in the dock area that looks like a pull-down menu (the fourth one
down) is the object that represents the main menu. In Figure 2-5, it has a highlighted border to

indicate that it’s selected.
Below the main menu icon in the dock is an icon that looks like a window, which is in fact what it is.
The Cocoa Application project template we used to create this project assumed that we would have
at least one window in our application, and it created that window for us. We’ll use this window to
lay out the contents of the window that will be displayed when our program is launched. Select the
window icon and our application’s new, empty, main window will appear on the graph paper.
The Library
The Library pane in the lower right-hand corner acts as a palette, a collection of objects we can use
to build our application’s interface. In Mountain Lion, there are 134 different object types to play with
here. The Library starts off showing a File Template Library, but there are four kinds of resources
that can be shown here: File Templates, Code Snippets, Objects, and Media. All the user-interface
elements that we’ll want to use are under the Objects view. We scroll through the library looking for
the item we want to use, then drag that item into the appropriate Xcode pane. Select the icon that
represents the Object Library view, or press ^⌥⌘3. The screen should look like Figure 2-6.
www.it-ebooks.info

12 CHAPTER 2: Hello, World
Take a minute to scroll through the different UI objects in the library: buttons, sliders, text fields,
labels, browsers, even an OpenGL view!
Dragging Out a Label
The Object Library pane will show a list of items that can be dragged to our application window to
build our application’s interface. Let’s drag one over now. We’re going to use an object called Label,
which is used to display static text—text that the user can’t edit. Drag a label over to the window.
In the Object Library view, scroll down about a dozen items to one called Label. Click directly on the
Label in the library and drag it over to the application’s main window (the window labeled Chapter2).
Doing this will add a new label to our application’s window (Figure 2-7).
Figure 2-6. MainMenu.xib showing our new, empty window and the Object Library
www.it-ebooks.info

13CHAPTER 2: Hello, World

Figure 2-7. Dragging a label out to the window
Tip Instead of scrolling down through the list as we did, we could have just typed the word “label”
into the search field at the bottom of the Library pane. This would have filtered down the list to show
only those objects in the library with the word “label” in their name or description.
Now that we’ve got a label, let’s change it. Double-click the label. It should become editable and
selected. Because the existing text is selected, we can just type our new text and it will replace what
was there before. Go ahead and type “Hello, World!”, which is infinitely less boring than “Label.” (If
you’re feeling rebellious, you could type something else, but don’t blame us if the Tiki Gods come
after you!)
Using the Blue Guidelines
When you’re done editing the label, press return to commit the changes, which will take that label
out of editing mode. Next, click and drag the label toward the left side of the window. As it gets
near the left edge of the window, there will be a dashed blue line to the left of the text (Figure 2-8).
Interface Builder uses these blue guidelines to indicate that the dragged item is aligned properly with
the items around it. In this case, the guideline is indicating that the label is the proper distance from
the left edge of the window.
www.it-ebooks.info

14 CHAPTER 2: Hello, World
Note One of the things that has made using the Mac such a pleasant experience over the years has
been the consistency of the user interface. In the vast majority of Mac applications, you can count on
the ability to press ⌘W to close a window, ⌘S to save, and ⌘P to print, regardless of what program
you are in. If you’re going to write software for the Mac, you should know these “rules of consistency.”
Apple lays out these rules in their Human Interface Guidelines (also know as the HIG). Interface
Builder’s little blue guidelines are there expressly to make it easier for you to conform to the Human
Interface Guidelines. You can find a copy of the HIG at />mac/#documentation/UserExperience/Conceptual/AppleHIGuidelines.
Figure 2-8. When we move the object near the edges, blue lines appear
The Inspector
The Library area takes up the bottom third or so of the Utility area on the right-hand side of the
Xcode window. Another important Interface Builder tool is situated right above the Library, taking up

the upper two-thirds of the Utility area on the right. This is called the Inspector. The Inspector is a
context-sensitive pane that displays information about the currently selected object. Click a window
and the Inspector displays information about that window (Figure 2-9). Click the label and the
Inspector displays information about that label. You get the idea.
www.it-ebooks.info

15CHAPTER 2: Hello, World
Take a look at the Inspector panel shown in Figure 2-9. Notice the eight small icons that span the top
of the panel. When pressed, each icon will turn the panel into one of eight different inspector types.
There is also a keyboard shortcut for each of the Inspectors, starting with ⌥⌘1 to go to the left-
most inspector (the File Inspector) through ⌥⌘8 for the right-most Inspector. When working in
Interface Builder mode, the Attributes and Connections Inspectors will be the ones we use the most.
Table 2-1 lists the command-key equivalents for each of the eight Inspectors.
Figure 2-9. The Inspector showing attributes for the window
www.it-ebooks.info

16 CHAPTER 2: Hello, World
Figure 2-10. The Attribute Inspector showing all the attributes of the label that can be edited in Interface Builder
The Attributes Inspector
Let’s start off with a look at the Attributes Inspector. (If you don’t see it, press ⌥⌘4 to show that
pane in the Utility area, then single-click your label.) The Inspector should look like Figure 2-10.
Table 2-1. Key Combination Shortcuts for Interface Builder’s Inspectors
Key Combination
Inspector
⌥⌘1 File Inspector
⌥⌘2 Quick Help Inspector
⌥⌘3 Identity Inspector
⌥⌘4 Attributes Inspector
⌥⌘5 Size Inspector
⌥⌘6 Connections Inspector

⌥⌘7 Bindings Inspector
⌥⌘8 View Effects Inspector
We can use the Attributes Inspector to change the appearance of our label. We can change
attributes like text alignment, border, and scrolling behavior. Interestingly, several of these fields will
actually do nothing. Go ahead and type something into the Placeholder field. Doesn’t change the
appearance of the label at all, does it?
www.it-ebooks.info

17CHAPTER 2: Hello, World
What’s going on here? When we pull a label out of the library, we are grabbing an instance of the
NSTextField class. The NSTextField class is used for both static and editable text fields. In an
editable text field, the placeholder is that gray text we see in some text fields when they are empty,
which tells us what the field is for.
When a text field is configured as a label, there’s no need for a placeholder. It doesn’t hurt to provide
one, but it doesn’t help, either.
There are too many context-specific attributes to be able to enumerate them all in this book, but we
will walk through the non-obvious ones. As you make your way through the book, you’ll become
comfortable with most of the attributes that you find yourself using.
Let’s change the size of the label. If the label is not selected, single-click it to select it. A dot should
appear on either side of the label. These dots are resize handles, which allow us to change the size
of the selected item. Most objects in Interface Builder have four resize handles, one in each corner,
which allow us to adjust the size in all four directions. Certain items, like labels, have only two resize
handles. The label’s attributes (the size of its font in particular) determine the vertical size of the label.
We don’t change the height of the label by resizing it. We only use the resize handles to change the
width of the label.
Let’s center the label. Make sure the left side of the label is lined up with the blue guideline near the
left edge of the window. Then, grab the right resize handle and drag out the label until we get to the
blue guideline near the right edge of the window. When done, the label should look like Figure 2-11.
Figure 2-11. Our application’s window in Interface Builder, after resizing the label
www.it-ebooks.info

18 CHAPTER 2: Hello, World
Now, with the label still selected, look for a row of buttons labeled Alignment in the Attributes
Inspector, and select the Center Text button (Figure 2-12). Also, look for a pop-up menu labeled
Behavior, and set it to be Selectable, which tells Cocoa that we want to allow the user to copy this
label to the pasteboard if they want. By default, labels are not selectable, but we just changed that.
Figure 2-12. The alignment buttons in the Attributes Inspector for the label, set to centered text
Change the Label’s Color and Font
Let’s make one final change to our window’s content: let’s change the font, size, and color of the
text. If we look at the Attributes Inspector, we can probably figure out how to change the color of the
text, but there are some wrinkles to setting the font and size.
First, let’s set the color. Look in the Attributes Inspector for a color well labeled Text Color. If we click
it, the standard Mac OS X color picker will appear (Figure 2-13) and we can select the color we want
for the text. Go ahead and do that now, picking whatever color strikes your fancy.
www.it-ebooks.info

19CHAPTER 2: Hello, World
Xcode itself is built using Cocoa and leverages a lot of built-in Cocoa functionality, such as the
standard color picker. The Apple engineers do not want to reinvent the wheel any more than you do.
When you write your own applications, you’ll be able to use this exact same color picker with just a
few lines of code or, in some situations, without writing any code at all.
Another piece of built-in Mac OS X functionality that you’ll be able to use in your applications is the
standard font window, which allows you to change the font, size, and attributes of selected text.
When creating applications that will be distributed to others, it is important to realize that you could
select fonts that your user won’t have installed. In general, for standard GUI components, you’re
probably better not changing the fonts at all. Consistent font usage is an important part of the GUI
consistency that the Mac is known for. Most labels, buttons, and other controls use the Lucida
Grande font by default. You can change the size of some labels, and switch them between bold and
regular to highlight different things, but leave the font itself as it is. Xcode provides guidance in the
Font field of the Attributes Inspector, as shown in Figure 2-14. Although the Font panel is available,
Xcode also offers a callout window with quick access to the system-default fonts. If you know that

you want the bold version of whatever is currently the system font, you can get it easily from the Font
pull-down menu in this callout. Generally, this is what you’ll want to use for common user-interface
elements, rather than explicitly setting the font.
Figure 2-13. The standard Mac OS X color picker is used to select colors in Cocoa applications. Here, we’re using it in Interface
Builder to set the color of our text
www.it-ebooks.info

20 CHAPTER 2: Hello, World
Press ^⇧⌘T to bring up the font window in Xcode. Make sure that our label is still selected (look for the
resize handles), and also make sure that our application’s main window is still the front-most window.
Once we have our label looking just the way we like, we’ll put some finishing touches to our
application, then run it. We’re almost there!
Creating the Application Icon
One thing that all applications need is an icon. Mac OS X uses a special format for icons that
bundles multiple images together in order to provide images in multiple sizes and resolutions for use
when zooming and for devices with Retina displays. However, Xcode will prepare this format for us.
We just need to name our images appropriately and put them into a folder with a .iconset extension.
The naming convention is pretty straightforward. An example image name is
Each image’s name starts with icon_, followed by the resolution, followed by an optional marker to
indicate high-resolution artwork, followed by the file extension, such as .png. The full set of sizes
utilized by Cocoa is 16 × 16, 32 × 32, 128 × 128, 256 × 256, and 512 × 512. Each of these can
optionally have a high-resolution marker of @2x. Note that the sizes are in screen points, not pixels;
a 512 × 512@2x file has a size of 1024 ×1024 pixels. Cocoa knows whether our app is running on a
machine with a Retina or other high-resolution display and will choose the best bitmap to use given
the screen’s pixel density and the needed size. If we don’t provide the image that Cocoa wants, it
will scale one of the images that we did provide. We can provide a big image with incredible detail
for when running on a Mac with a Retina display, but that might not look exactly the way we want.
Support for multiple images means that we can tailor how the icon appears at smaller sizes.
Figure 2-14. Xcode has a special font-selector callout to give easy access to the default fonts
www.it-ebooks.info


21CHAPTER 2: Hello, World
We need to start our icon in an image-editing program such as Photoshop, Pixelmator, or GIMP.
The original file should be a size of 1024 × 1024 pixels and saved in a standard image format that
supports alpha channels (transparency), such as TIFF, PSD, or PNG. For this example, we’re working
with .png files. We’ll save it as We can then scale down the image in whatever
method works best. This would typically be done by using our image editor’s resize functions and
then cleaning it up by hand as necessary.
To save you the trouble of creating your own icon, we’ve provided a hello world.iconset folder with
images that you can add to your project. You’ll find this folder in the downloaded project files for
Chapter 2. If you’d rather roll your own, go right ahead, using the same naming conventions in the
hello world.iconset folder for your images.
Adding an Icon to our Project
Whether you created an icon yourself or you are using ours, it’s time to add the icon to the project in
Xcode. To do this, select the Project in the Navigator area on the left side of the screen. It’ll be the top
item in the Project Navigator view; in our case, it’s labeled “Chapter2.” The project summary info will
show up in the Editor area in the middle of the window, and the Chapter2 Target should be selected.
Drag the hello world.iconset folder from the Finder to Xcode’s App Icon well in the middle of the
window, as shown in Figure 2-15. This tells Xcode that we want to import this file into our project.
Figure 2-15. Dragging a file to the App Icon well to add the icon to the Xcode project
www.it-ebooks.info

×