Xcode Quick Start Guide
Xcode Quick Start Guide
Xcode Quick Start Guide
2011-03-02
Apple Inc. 2011 Apple Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer for personal use only and to print copies of documentation for personal use provided that the documentation contains Apples copyright notice. The Apple logo is a trademark of Apple Inc. No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the technology described in this document. This document is intended to assist application developers to develop applications only for Apple-labeled computers. Apple Inc. 1 Infinite Loop Cupertino, CA 95014 408-996-1010 App Store is a service mark of Apple Inc. Apple, the Apple logo, Cocoa, iPod, Mac, Mac OS, Objective-C, Quartz, and Xcode are trademarks of Apple Inc., registered in the United States and other countries. IOS is a trademark or registered trademark of Cisco in the U.S. and other countries and is used under license.
Even though Apple has reviewed this document, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS DOCUMENT IS PROVIDED AS IS, AND YOU, THE READER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY. IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages. THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make any modification, extension, or addition to this warranty.
Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state.
Contents
Introduction
About Xcode 7
At a Glance 7 The Workspace Window Manages Projects 7 Task-Based Help Provides Focused Assistance 8 How to Use This Document 8 See Also 8
Chapter 1
Chapter 2
3
2011-03-02 | 2011 Apple Inc. All Rights Reserved.
CONTENTS
4
2011-03-02 | 2011 Apple Inc. All Rights Reserved.
Chapter 2
5
2011-03-02 | 2011 Apple Inc. All Rights Reserved.
6
2011-03-02 | 2011 Apple Inc. All Rights Reserved.
INTRODUCTION
About Xcode
Xcode is a highly customizable integrated development environment (IDE) with many features for creating an efficient and effective working environment.
At a Glance
Xcode facilitates the development of software products of all sizes, from iPod games to enterprise solutions. The Xcode application is the main component of the Xcode toolset. It groups most of the tools you need to develop software in a streamlined and interactive user interface.
Toolbar
Project navigator
Source editor
At a Glance
2011-03-02 | 2011 Apple Inc. All Rights Reserved.
INTRODUCTION
About Xcode
The Project Navigator is Where You Organize the Main Components of Your Projects
The project navigator lets you find project components quickly. For example, you can add and modify the groups in the project navigator to reduce clutter.
See Also
Xcode 4 User Guide provides information about the essential tasks you perform as you develop your products.
CHAPTER 1
This short tutorial shows how to create a project for a Mac application that prints text in a window. Working through this tutorial, you get acquainted with the software-creation workflow in Xcode: creating the project, designing the user interface, writing code, and running the application. You also learn how to fix code errors Xcode detects as you write the code, and you get an introduction to the Xcode debugging facilities. Hello is a simple application. When the user launches it, a window appears, displaying the text Hello, World!, similar to the window shown in Figure 1-1. Figure 1-1 The Hello application in action
Under the hood, the user interface consists of a window (an NSWindow object) that contains a view (an NSView object). Views know how to display data. These objects have a built-in method through which Cocoa manages drawing into the view. You need to provide the code that draws the Hello, World! message. In this tutorial you use Objective-C and the Cocoa framework to create a view and implement the drawing routine. You dont need to be familiar with Cocoa or Objective-C to complete this tutorial, but you should be familiar with programming in some language, preferably a C-based or object-oriented language. To perform the tutorial you must have Xcode installed on your Mac. Visit developer.apple.com to download Xcode. In this tutorial you:
9
2011-03-02 | 2011 Apple Inc. All Rights Reserved.
CHAPTER 1
Lay out the user interface of the Hello window Write the code that displays the message on the Hello window Build and run the Hello application View the messages produced by building the Hello application
4.
10
CHAPTER 1
App Store Category: None. Create Document-Based Application: not selected, which disallows entry into the Document Class and Document Extension fields. Use Core Data: not selected. Include Unit Tests: not selected.
5.
In the dialog that appears, navigate to the file-system location where you want to place the project directory (for example, the Desktop), ensure the Create local git repository for this project option is not selected, and click Create.
11
CHAPTER 1
After creating the project directory in your file system, Xcode opens it in a workspace window.
The project contents appear in a pane (known as the project navigator) on the left side of the window. The first item in the group represents the project, and its named after the product name you specified when you created the project. Xcode groups the components of the Hello project in three groups:
Hello: Contains the files that make up the project. These files include source code files and a user-interface file. This group also contains a subgroup, named Supporting Files, that contains files used in supporting tasks. You dont modify these files in this tutorial. Frameworks: Identifies frameworks or libraries your code relies on for its functionality; for example, the Cocoa framework. Products: Contains the products your project produces, such as an application.
12
CHAPTER 1
Note: If the New File command is dimmed in the New menu, ensure that the Hello workspace window has the focus (that it is the frontmost window) by clicking inside it. The commands Xcode makes available in the menu bar depend on the window that has the focus. Many project-related commands are not available when a window other than a workspace window has the focus. 2. In the Mac OS X group, select Cocoa, then select the Objective-C class template, and click Next.
13
CHAPTER 1
3.
Specify that the new file is a subclass of NSView, and click Next:
4.
In the dialog that appears, enter HelloView.m as the filename, choose the Hello group (which uses a yellow folder icon) from the Group pop-up menu, and click Save.
14
CHAPTER 1
Xcode adds the header and implementation files for the HelloView class to the project. They are listed in the project navigator.
15
CHAPTER 1
This editor has two major areas, highlighted in Figure 1-2: the dock (on the left) and the canvas (on the right). The dock displays the objects in the nib file. The canvas is where you lay out your applications user interface using the objects in the nib file.
Figure 1-2
2. 3.
If the canvas shows the Hello menu bar object, as the previous screenshot does, click its close box (x) to remove it from the canvas. If the dock appears in list view (Figure 1-3) instead of icon view (Figure 1-2), click the highlighted button to change it to icon view.
Figure 1-3
16
CHAPTER 1
4.
Click the Window - Hello item in the dock to display the Hello window in the canvas.
5. 6.
Choose View > Navigators > Hide Navigator to narrow the focus of the workspace (you wont be navigating the project in the next few steps). Choose View > Utilities > Show Utilities.
17
CHAPTER 1
The utility area (Figure 1-4) contains two panes: the inspector pane (top) and the library pane (bottom). The library pane contains libraries for file templates, code snippets, objects, and media.
Figure 1-4
7.
Display the Object library by choosing View > Utilities > Object Library. Make the library pane taller by dragging its selector bar up. (This also makes the inspector pane shorter.)
18
CHAPTER 1
8.
From the Object Library pop-up menu, choose Cocoa > Layout Views.
9.
Drag the Custom View object from the library to the Hello window in the canvas.
Youve created an instance of the NSView class and added it to the window.
19
CHAPTER 1
10. Resize the newly added view by dragging its sides to the Hello windows borders, so that it occupies the entire content area of the Hello window.
11. Choose View > Utilities > Identity Inspector. The Identity inspector lets you specify details about user-interface elements that identify them to users of your application (tooltips, also called help tags) and to the system (class, runtime attributes, object ID, and so on).
20
CHAPTER 1
12. In the Identity inspector, choose HelloView from the Class pop-up menu in the Custom Class group.
Notice that the label for the view changes from Custom View to HelloView. 13. Choose View > Utilities > Size Inspector.
In the Size inspector you can enter precise values for positioning and sizing controls. The Autosizing area lets you specify how (and whether) controls change size and position as the enclosing window changes size. (You can also change the layout by moving and resizing controls on the Interface Builder canvas.) 14. In the Autosizing area, click the vertical and horizontal dotted lines in the inner square.
21
CHAPTER 1
Notice that the dotted lines change to solid ones. Solid lines in the inner square indicate the directions the view resizes automatically. In this case, the view resizes vertically and horizontally when the user changes the window size. The example animation to the right of the Autosizing area provides a simulation of the new sizing behavior. There is much more to Interface Builder than youve seen here. When you develop more advanced applications, you use the inspectors to set connections to associate the code you write to interact with user-interface objects.
Gutter
Focus ribbon
The gutter displays line numbers (when the Line numbers option in Text Editing preferences is selected; see Text Editing Preferences Help) and the location of breakpoints, errors, and warnings in the file. The focus ribbon helps you to concentrate your attention on your code by:
Identifying the scope of a block of code Allowing you to hide blocks of code
View related files Move backward and forward through the set of project files youve viewed Jump to another location within the current file or to another file in the project
22
CHAPTER 1
To enter the source code for the Hello application: 1. 2. 3. Choose View > Navigators > Project. Choose View > Utilities > Hide Utilities. In the project navigator, select HelloView.m to open it in the source editor. Listing 1-1 shows the initial implementation of the HelloView class. Initial implementation of the HelloView class
Listing 1-1
#import "HelloView.h" @implementation HelloView - (id)initWithFrame:(NSRect)frame { if ((self = [super initWithFrame:frame])) { // Initialization code here. } return self; } - (void)dealloc { // Clean-up code here. [super dealloc]; } - (void)drawRect:(NSRect)dirtyRect { // Drawing code here. } @end
4.
23
CHAPTER 1
Notice that the gutter shows a warning icon. This means that Xcode has found a problem in the code you just typed. To get information about the problem, click the warning icon. Xcode describes the problem and offers a solution.
Double-click Insert "@" (or press Return) to convert the C string into an Objective-C string object. Youve just taken advantage of Live Issues (in-line issue detection and diagnosis) and Fix-it (automatic issue correction). The fixed code line should look like this:
NSString *hello = @"Hello, World!";
This code line creates the string that the Hello application draws into the view. Fix-it detects another another problem: The hello variable is unused in the drawRect: method. Thats why theres still a warning icon in the gutter. Youll fix that problem shortly. 5. Type this text below the code line you added in the previous step:
NSPoint point = NSMake
24
CHAPTER 1
As you type the name of a symbol, Xcode suggests completions to what youre typing.
This is code completion. You specify whether Xcode provides completions as you type in Text Editing preferences. Because Xcode sees that youre assigning the functions return value to a variable of type NSPoint, Xcode selects the NSMakePoint completion in the completion list. Press Return to choose that completion. Xcode highlights the first parameter in the completion. 6. Type 15, press Tab, and type 75. Add a semicolon to the end of the line. The code line should look like this:
NSPoint point = NSMakePoint(15, 75);
This call creates a point at the specified coordinates. This point is the origin for drawing the message.
25
CHAPTER 1
7.
Place the cursor on the NSMakePoint function name, and choose Help > Quick Help for Selected Item.
Quick Help provides a summary of the API reference for the selected symbol. From the Quick Help window you can access the rest of the developer library to get in-depth information about the symbol. Tip: You can also hold down Option while moving the pointer over your code. When you put the pointer over a symbol, Xcode underlines the symbol. Click the symbol while holding down Option to display the Quick Help window. 8. Complete the implementation of the drawRect: method so that it looks like Listing 1-2. Implementation of the drawRect: method
Listing 1-2
- (void)drawRect:(NSRect)dirtyRect { NSString *hello = @"Hello, World!"; NSPoint point = NSMakePoint(15, 75); NSMutableDictionary *font_attributes = [[NSMutableDictionary alloc] init]; NSFont *font = [NSFont fontWithName:@"Futura-MediumItalic" size:42]; [font_attributes setObject:font forKey:NSFontAttributeName]; [hello drawAtPoint:point withAttributes:font_attributes]; [font_attributes release]; }
After typing the code, correct transcribing errors found by Fix-it (the code provided has no problems).
26
CHAPTER 1
9.
Add a breakpoint to the drawRect: method. Add the breakpoint by clicking the gutter to the left of the code line with the assignment to the font variable. Although the drawRect: method has no problems, adding a breakpoint to it allows you to familiarize yourself with the Xcode debugging facilities when you run the Hello application.
Notice that adding the breakpoint automatically activates breakpoints for your projectthe Breakpoints toolbar button has a pushed-in appearance.
27
CHAPTER 1
Figure 1-6 shows a debugging session using the debug navigator (on the left), the source editor (on the right), and the debug area (below the source editor) to get information about the running code.
Figure 1-6
Notice that the source editor can display the values of variables within a scope. When you place the pointer over the hello variable, the source editor displays information about the variable in a datatip. The debug area contains the variables pane and the console pane. The variables pane shows information about the variables of the drawRect: method. The console pane shows your programs console output. You can also enter commands directly to the debugger in the console pane. 2. Choose Product > Debug > Continue to continue execution of the Hello application.
28
CHAPTER 1
The window of the Hello application appears with the Hello, World! message displayed in its bottom-left corner.
3.
Choose Hello > Quit Hello or click the Stop toolbar button in the workspace window to stop the Hello application.
29
CHAPTER 1
Selecting an operation in the log viewer (Figure 1-7) reveals the transcript button on the right side of the operation. Click the transcript button to display details about the operation.
Figure 1-7
30
CHAPTER 2
31
CHAPTER 2
Figure 2-1
As you create this user interface, youll explore some of the commonly-used features of Interface Builder. Its time to get started.
32
CHAPTER 2
d.
Click Next.
2.
Specify options for the new project. a. b. c. Name the product QCDemo. Specify your company identifier (or accept the default identifier). Make sure that no other options are set.
33
CHAPTER 2
d.
Click Next.
3.
Create the project. a. b. c. Select a location for the new project folder. Make sure that the Source Control option is not set. Click Create.
4.
Add the Quartz framework to the projects target. a. b. In the project navigator, select the QCDemo project. In the project editor, under Targets, select QCDemo.
34
CHAPTER 2
c.
In the Summary pane, under Linked Frameworks and Libraries, click the Add (+) button.
d.
Choose Quartz.framework from the list and click the Add button. (Tip: Type quartz into the text field to filter the list.)
5.
Add source code to include the Quartz framework header. a. b. c. In the project navigator, select the file QCDemoAppDelegate.h. In the source editor, find the line #import <Cocoa/Cocoa.h>. After this line, add the line #import <Quartz/Quartz.h>.
35
CHAPTER 2
Youll make more changes to this file later in the tutorial. 6. Open the Interface Builder document. a. b. c. d. In the project navigator, find the nib file MainMenu.xib. Click MainMenu.xib to open the document in the Interface Builder editor pane. In the Xcode menu bar, choose View > Navigators > Hide Navigator to narrow the focus of the workspace. If the dock on the left does not look like the figure below, click the button in the lower left corner to switch the dock to outline view.
7.
Set the size attributes of the QCDemo window. a. b. c. d. In the Xcode menu, choose View > Utilities > Size Inspector. In the outline view at the left side of the Interface Builder editor, select the window. Until you select it, the window does not appear on the Interface Builder canvas. In the Size inspector, set the windows width to 480 and height to 420. Select the Minimum Size option.
36
CHAPTER 2
e.
8.
Add a Quartz Composer view to the QCDemo window. a. b. c. Make sure the Object library is visible in the pane below the Size inspector. If not, choose View > Utilities > Object Library. Enter quartz composer in the search field at the bottom of the library. Drag the Quartz Composer view from the library to the QCDemo window.
37
CHAPTER 2
9.
Set the size attributes of the Quartz Composer view. a. Make sure the Quartz Composer view is still selected (Window QCDemo > View > View in the outline view). There are several ways to select an object in Interface Builder. If an object is nested inside another object, you can select it in the outline view, the jump bar, or by clicking the object on the canvas. The jump bar is located just above the editor pane.
b. c. d.
In the Size inspector, ensure that Origin is set to the lower-left corner, as shown in the figure below. Ensure that the Show menu is set to Frame Rectangle. Set the views X position to 0 and Y position to 60.
38
CHAPTER 2
e.
f.
Set the views autosizing control as shown in the figure below. You set the autosizing behavior for this view by clicking every arrow and line in the control so that each changes from a dotted line to a solid line.
10. Select an initial composition for the Quartz Composer view. a. In the Xcode menu bar, choose View > Utilities > Attributes Inspector.
39
CHAPTER 2
b.
c.
Load the Quartz Composer composition at the following location inside the System folder:
/System/Library/Screen Savers/Shell.qtz
This composition is available as a screen saver in System Preferences. d. Select the Start Playing Automatically option.
11. Run a simulation of the QCDemo user interface. Interface Builder includes a separate application called Cocoa Simulator. You can use Cocoa Simulator to preview your user interface as you work on it. a. b. Choose Editor > Simulate Document to start the simulation and display the composition. Try enlarging the QCDemo window and observe what happens to the composition. The composition is automatically resized because of the way you changed the autosizing behavior of the Quartz Composer view. Press Command-Q to quit the simulation.
c.
12. Build and run the QCDemo application. a. b. c. d. Click the Run button at the left end of the Xcode toolbar. If youre asked whether you want to save documents before building, click Save. Verify that the application runs correctly by moving and resizing the window. Press Command-Q or click the Stop button to quit the application.
40
CHAPTER 2
b. c. d.
In the library pane, type button in the search field. Drag a push button from the library to the open area at the bottom of the QCDemo window. Use the horizontal and vertical guides to position the button in the lower-right corner of the window.
2.
Set the attributes of the push button. a. Verify that the button is selected. It should have a handle at either end.
If the button cell is selected instead of the button itself, you wont see the buttons handles. To select the button, click anywhere in the canvas outside of the button, then click the button again. b. c. Choose View > Utilities > Attributes Inspector. In the Attributes inspector, change the button type to Toggle.
41
CHAPTER 2
d.
Change the buttons title to Pause and set its alternate title to Play. Be sure to press Tab after entering the alternate title.
3.
Set the autosizing behavior of the button. a. b. Choose View > Utilities > Size Inspector. In the Size inspector, set the buttons autosizing control as shown in the figure below. Tip: if you dont see the autosizing control, make sure youve selected the push button and not the button cell.
4.
Connect the button to the Quartz Composer views play: action. This action method is implemented for you in the QCView class. For more information about this class, see QCView Class Reference. a. b. c. In the outline view, select the Quartz Composer view. Choose View > Utilities > Connections Inspector. In the Connections inspector, find play: under Received Actions.
42
CHAPTER 2
d.
Drag from the circle at the right of the play: action to the Pause/Play button. Release the mouse button to complete the connection.
5.
Run a simulation of the QCDemo user interface. a. b. c. d. Choose Editor > Simulate Document to start the simulation. Try toggling the Pause/Play button to make sure it works as expected. Try enlarging the window to make sure the button stays in the corner where it belongs. Press Command-Q to quit the simulation.
Set the attributes of the push button. a. b. Verify that the button in the lower-left corner of the window is selected. In the Attributes inspector, set the buttons type to Momentary Push In.
43
CHAPTER 2
c. 3.
In the Size inspector, set the buttons autosizing control as shown in the figure below.
4.
Run a simulation of the QCDemo user interface. a. b. c. d. Choose Editor > Simulate Document to start the simulation. Try enlarging the window to make sure the Load button stays in the corner where it belongs. Try clicking the Load button. The button should highlight when clicked. Press Command-Q to quit the simulation.
2.
44
CHAPTER 2
a.
Control-drag from the window to below the interface definition in the QCDemoAppDelegate.h file. You can Control-drag from the window in the outline view (as shown below), or from the windows title bar in the canvas. In the outline view, the window is labeled Window QCDemo An Insert . Outlet flag indicates where the connection will be made.
b.
In the dialog that appears, specify an outlet named qcWindow of class type NSWindow.
c.
Click Connect. Interface Builder creates the connection and inserts code into the QCDemoAppDelegate class. For example, Interface Builder inserts the following line into QCDemoAppDelegate.h:
@property (assign) IBOutlet NSWindow *qcWindow;
At runtime, this property is set to the address of the window. Later in this tutorial, you will add code to QCDemoAppDelegate.m that uses this property. 3. Add an outlet connection from the Quartz Composer view to the QCDemoAppDelegate class.
45
CHAPTER 2
a.
Control-drag from the Quartz Composer view to below the interface definition in the QCDemoAppDelegate.h file.
b.
In the dialog that appears, specify an outlet named qcView of class type QCView.
c.
Click Connect. Again, Interface Builder creates the connection and inserts code into the QCDemoAppDelegate class. Interface Builder inserts the following line into QCDemoAppDelegate.h:
@property (assign) IBOutlet QCView *qcView;
At runtime, this property is set to the address of the Quartz Composer view. Later in this tutorial, you will add code to QCDemoAppDelegate.m that uses this property. 4. Add an action connection from the Load button to the QCDemoAppDelegate class.
46
CHAPTER 2
a.
Control-drag from the Load button to below the interface definition in the QCDemoAppDelegate.h file.
b.
Change the connection type to Action and specify an action named loadComposition of type id.
c.
Click Connect. Interface Builder creates the connection and inserts code into the QCDemoAppDelegate class. For example, Interface Builder declares the new action method in QCDemoAppDelegate.h:
- (IBAction)loadComposition:(id)sender;
In addition, Interface Builder adds an empty definition of the action method to QCDemoAppDelegate.m. Youll add the necessary code to define this method in the next section.
47
CHAPTER 2
In the project navigator, select the file QCDemoAppDelegate.h. The file should look like Listing 2-1 (Interface Builder added the highlighted lines). The QCDemoAppDelegate header file
Listing 2-1
#import <Cocoa/Cocoa.h> #import <Quartz/Quartz.h> @interface QCDemoAppDelegate : NSObject <NSApplicationDelegate> { @private NSWindow *window; NSWindow *qcWindow; QCView *qcView; } @property (assign) IBOutlet NSWindow *qcWindow; @property (assign) IBOutlet QCView *qcView; - (IBAction)loadComposition:(id)sender; @property (assign) IBOutlet NSWindow *window; @end
3.
Now select the file QCDemoAppDelegate.m. The file should look like Listing 2-2 (Interface Builder added the highlighted lines). The QCDemoAppDelegate implementation file
Listing 2-2
#import "QCDemoAppDelegate.h" @implementation QCDemoAppDelegate @synthesize qcWindow; @synthesize qcView; @synthesize window;
48
CHAPTER 2
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { // Insert code here to initialize your application } - (IBAction)loadComposition:(id)sender { } @end
49
CHAPTER 2
a.
Click Run. If youre asked whether you want to save documents before building, click Save.
b.
c.
Use the dialog to load another Quartz Composer composition. For example, load:
/System/Library/Screen Savers/Arabesque.qtz
50
CHAPTER 2
2.
Whats Next?
Now that your project is complete, you may want to do some further reading. To learn more about the concepts and tasks introduced here, read the chapter on designing user interfaces in Xcode 4 User Guide.
Whats Next?
2011-03-02 | 2011 Apple Inc. All Rights Reserved.
51
CHAPTER 2
52
Whats Next?
2011-03-02 | 2011 Apple Inc. All Rights Reserved.
REVISION HISTORY
This table describes the changes to Xcode Quick Start Guide. Date 2011-03-02 Notes New document that provides a hands-on introduction to Xcode.
53
2011-03-02 | 2011 Apple Inc. All Rights Reserved.
REVISION HISTORY
54
2011-03-02 | 2011 Apple Inc. All Rights Reserved.