Now that you’ve learned a bit about the puzzle pieces needed to build an SDK program, you’re ready to start programming. The main purpose of this chapter is to show you how Xcode, the SDK’s main development environment, works. Via a traditional Hello, World! program, we look at the parts of a standard SDK program. You’ll build it first for the iPhone and then build it again for the iPad so you can see how to construct a basic application for either device. We also examine how to create new classes of objects; and with that under your belt, we finish up by looking at some of Xcode’s most interesting features.
Apple programming begins with Xcode, an integrated development environment (IDE) that you can call up from the Developer directory. To write iPhone or iPad programs, you must have downloaded the iPhone SDK, as discussed in the previous chapter. After you’ve done that, choosing File > New Project gets you started. You’re immediately asked to select a template for your new project.
The template you choose will fill your project with default frameworks, default files, default objects, and even default code. As you’ll see, it’ll be a great help in jump-starting your own coding. For your first program, go with the simplest template you can find: Window-Based Application.
After you select a template, you also need to name your project and choose where to save it; but when you’ve done that, you’re ready to start coding. Before we get there, let’s take a closer look at how the Xcode environment works.
When called up, Xcode displays one window. Figure 3.1 shows what it looks like for your first example project, helloworldxc.
As you can see, Xcode’s main project window includes three parts. Off to the left is a side pane that contains a listing of all the files that are being used in your project, organized by type. Whenever you need to add frameworks, images, databases, or other files to your projects, you do so here. The left pane also contains some other useful elements, in particular an Errors and Warnings item that you can click open to quickly see any problems in your compilation.
The upper-right pane contains an ungrouped list of files used by your project. When you click one of those, its contents appear in the lower-right pane. As you can see, even the simplest program includes over a half-dozen files. Table 3.1 summarizes what each is.
File |
Summary |
---|---|
project.app | A compiled application. |
*.framework | A standard framework included as part of your project. By default, every project should include Foundation, giving you access to NS objects; UIKit, giving you access to UI objects; and Core Graphics, giving you access to various graphics functions. We’ll talk later about adding additional frameworks. |
*.h | A header file, usually containing the @interface for a class. |
*.m | A source code file, usually containing the @implementation for a class. |
*.mm | A source code file with C++ code. Not used in this book. |
project_Prefix.pch | A file containing special prefix headers, which are imported into every one of your source code files. It’s here that the two main frameworks are imported. |
Info.plist | An XML property list. It contains a number of instructions for your program compilation, the most important of which is probably the reference to the .xib file used in your program. |
MainWindow.xib | An Interface Builder file, more broadly called a nib file. This is your connection to the interface design program that may be used to easily create interfaces for your project. We’ll discuss it in depth in the next chapter. |
In this chapter, we focus exclusively on header and source code files. In the next chapter, you’ll extend your work to include the .xib Interface Builder file.
To compile in Xcode, choose Build > Build and Run from the menus. Your program compiles and links. Then, it’s installed on the iPhone Simulator, and the iPhone Simulator starts it up. If you try this using the project you just created using the Window-Based Application template, you’ll see the whole process, resulting in an empty white screen displaying on your iPhone Simulator. Note that programs exist only on your Simulator (or in the iPhone); they can’t be run on your Macintosh directly.
If you want to later rerun a program that you’ve already compiled, you can do so in one of three ways. You can click the program’s button, which should now appear in your Simulator. Or, you can choose Run > Run from within Xcode. Finally, you can choose Build and Go in Xcode, which builds only if required and then executes your program.
That’s it! With a rudimentary understanding of Xcode now in hand, you’re ready to write your first SDK program.
As we already noted, you should begin every project by choosing File > New Project, choosing a template, and naming your file. For your first sample project, select the Window-Based Application template, and use the name Helloworldxc. Make sure you select iPhone from the Product drop-down menu.
Before you start writing new code, you need a basic understanding of what’s there already, so we examine the contents of the three most important files that your basic template created: main.m, helloworldxcAppDelegate.h, and helloworldxcAppDelegate.m.
The first file created by Xcode is main.m, which contains the main function. main.m comes with standard code preinstalled for you, as you can see here:
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
The creation of this main routine is automatic, and you generally shouldn’t have to fool with it at all. But it’s worth understanding what’s going on. You start with an #import directive, which you’ll recall is Objective-C’s substitute for #include. More specifically, you include the UIKit framework, the most important framework in Objective-C. This isn’t needed, because it’s also in the Prefix.pch file; but at least at the time of this writing, it’s part of the default main.m file.
You next create an NSAutoreleasePool. Recall that we mentioned this in our discussion of memory management in the previous chapter. It’s what supports the NSObject’s autorelease method. Also note that you release the pool after you’ve run your application’s main routine, following the standard rule that if you allocate the memory for an object, you must also release it.
The UIApplicationMain line creates your application and kicks off the event cycle. The function’s arguments look like this:
int UIApplicationMain (
int argc,
char *argv[],
NSString *principalClassName,
NSString *delegateClassName
);
As with the rest of the main.m file, you should never have to change this. But we nevertheless briefly touch on what the latter two arguments mean—although they’ll usually be set to their defaults, thanks to the nil arguments.
principalClassName defines the application’s main class, which is UIApplication by default. This class does a lot of the action- and event-controlling for your program, topics that we’ll return to in chapter 6.
The UIApplication object is created as part of this startup routine, but you’ll note that no link to the object is provided. If you need to access it (and you will), you can use a UIApplication class method to do so:
[UIApplication sharedApplication];
This returns the application object. It’s typically sent as part of a nested message to a UIApplication method, as you’ll see in future chapters. For now, the application does two things of note: it calls up your default .xib file, and it interfaces with your application delegate.
The delegateClassName defines the application object’s delegate, an idea introduced in chapter 2. As noted there, this is the object that responds to some of the application’s messages, as defined by the UIApplicationDelegate protocol. Among other things, the application delegate must respond to lifecycle messages: most important, the applicationDidFinishLaunching: message, which runs your program’s content, as we’ll talk more about momentarily.
In Xcode’s templates, delegate class files always have the name projectApp-Delegate. Your program finds them, thanks to a delegate property that’s built into Interface Builder.
You could change the arguments sent to UIApplicationMain, and you could add other commands to the main.m file, but generally you don’t want to. The defaults should work fine for any program you’re likely to write in the near future. Let’s put main.m away for now and turn to the file where any programming starts: your application delegate.
As you’ve already seen, the application delegate is responsible for answering many of the application’s messages. You can refer to the previous chapter for a list of some of the more important ones or to Apple’s UIApplicationDelegate protocol reference for a complete listing.
More specifically, an application delegate should do the following:
Of these topics, the first is of importance to you now. Your application delegate files, helloworldxcAppDelegate.h and helloworldxcAppDelegate.m, get your program started.
Now that you’ve moved past main.m, you’re using classes, which is the sort of coding that makes up the vast majority of Objective-C code. Here are the contents of your first class’s header file, helloworldxcAppDelegate.h:
@interface helloworldxcAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
Again, there’s nothing to change here, but we want to examine the contents, both to reiterate some of the lessons you learned in the previous chapter and to give you a good foundation for work you’ll do in the future.
First, an interface line subclasses your delegate from NSObject (which is appropriate, because the app delegate is a nondisplaying class) and includes a promise to follow the UIApplicationDelegate protocol.
Next, you have the declaration of an instance variable, window. Finally, you declare that window as a property. Note that this statement includes some of the property attributes that we mentioned, here nonatomic and retain. This line also includes an IBOutlet statement, which tells you that the object was created in Interface Builder. We’ll examine this concept in more depth in the next chapter; for now, you only need to know that you have a window object already prepared for your use.
Although you won’t modify the header file in this example, you will in the future, and you’ll generally be repeating the patterns you see here: creating more instance variables, including IBOutlets, and defining more properties. You may also declare methods in this header file, something that this first header file doesn’t contain.
The following is the application delegate’s source code file, HelloworldxcAppDelegate.m. It’s here that you’ll place your new code:
#import "HelloworldxcAppDelegate.h"
@implementation HelloworldxcAppDelegate
@synthesize window;
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[window makeKeyAndVisible];
}
- (void)dealloc {
[window release];
[super dealloc];
}
@end
The source begins with an inclusion of the class’s header file and an @implementation statement. The window property is also synthesized.
It’s the content of the applicationDidFinishingLaunching method that’s of interest to you. As you’ll recall, that’s one of the iPhone OS lifecycle messages we touched on in chapter 2. Whenever an iPhone application gets entirely loaded into memory, it sends an applicationDidFinishingLaunching: message to your application delegate, running that method. Note that there’s already some code to display that Interface Builder–created window.
For this basic project, you’ll add all your new code to this same routine—such as an object that says Hello, World!
We’ve been promising for a while that you’ll be amazed by how simple it is to write things using the SDK. Granted, your Hello, World! program may not be as easy as a single printf statement; but nonetheless it’s pretty simple, considering that you’re dealing with a complex, windowed UI environment.
As promised, you write everything inside the applicationDidFinishingLaunching method, as shown in listing 3.1.
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[window setBackgroundColor:[UIColor redColor]];
CGRect textFieldFrame = CGRectMake(50, 50, 150,40);
UILabel *label = [[UILabel alloc] initWithFrame:textFieldFrame];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor redColor];
label.shadowColor = [UIColor blackColor];
label.font = [UIFont systemFontOfSize:24];
label.text = @"Hello, World!";
[window addSubview:label];
[window makeKeyAndVisible];
[label release];
}
Because this is your first look at real live Objective-C code, we examine everything in some depth.
You start by sending a message to your window object, telling it to set your background to red. Recall from our discussion of the header file that Interface Builder created the window. The IBOutlet that was defined in the header allows you to do manipulations of this sort.
Note that this line also makes use of a nested message, which we promised you’d see with some frequency. Here, you make a call to the UIColor class object and ask it to send you the red color. You then pass that on to your window.
In this book, we hit a lot of UIKit classes without explaining them in depth. That’s because the simpler objects all have standard interfaces; the only complexity is in which particular messages they accept. If you ever feel you need more information about a class, look at appendix A, which contains short descriptions of many objects, or see the complete class references available online at http://developer.apple.com (or in Xcode).
You next define where your text label is placed. You start that process by using CGRectMake to define a rectangle. Much as with Canvas, the SDK uses a grid with the origin (0,0) set at the upper left. Your rectangle’s starting point is thus 50 to the right and 50 down (50,50) from the origin. The rest of this line of code sets the rectangle to be 150 pixels wide and 40 pixels tall, which is enough room for your text.
You’ll use this rectangle as a frame, which is one of the methods you can use to define a view’s location.
Where your view goes is one of the most important parts of your view’s definition. Many classes use an initWithFrame: init method, inherited from UIView, which defines location as part of the object’s setup.
The frame is a rectangle that you’ve defined with a method like CGRectMake. Another common way to create a rectangular frame is to set it to take up your full screen:
[[UIScreen mainScreen] bounds];
Sometimes you’ll opt not to use the initWithFrame: method to create an object. UIButton is an example of a UIKit class that instead suggests you use a class factory method that lets you define a button shape.
In a situation like that, you must set your view’s location by hand. Fortunately, this is easy to do, because UIView also offers a number of properties that you can set to determine where your view goes, even after it’s been initialized.
UIView’s frame property can be passed a rectangle, just like the initWithFrame: method. Alternatively, you can use its center property to designate where the middle of the object goes and the bounds property to designate its size internal to its own coordinate system. All three of these properties are further explained in the UIView class reference.
Note that CGRectMake is a function, not a method. It takes arguments using the old, unlabeled style of C, rather than Objective-C’s more intuitive manner of using labeled arguments. When you get outside of Cocoa Touch, you’ll find that many frameworks use this older paradigm. For now, all you need to know is what it does and that you needn’t worry about releasing its memory. If you require more information, read the section “Using Core Foundation” in chapter 9.
The label is a simple class that allows you to print text on the screen. Figure 3.2 shows what the label (and the rest of the program) looks like.
As you’d expect, your label work begins with the creation of a label object. Note that you follow the standard methodology of nested object creation that we introduced in the previous chapter. First you use a class method to allocate the object, and then you use an instance method to initialize it.
Afterward, you send a number of messages to your object, this time using the dot shorthand. We offer this as a variation from the way you set the window’s background color. If you prefer, you can use the dot shorthand of window.backgroundColor there, too. The two ways to access properties are equivalent.
The most important of your messages sets the label’s text. You also set a font size and some colors. You can even give the text an attractive black shadow, to demonstrate how easy it is to do cool stuff using the iPhone OS’s objects.
Every object that you use from a framework is full of properties, methods, and notifications that you can take advantage of. The best place to look up all these is the class references.
The final steps in your program are all pretty simple and standard. First, you connect your label and your window by using the window’s addSubview method. This is a standard (and important!) method for adding views or view controllers to your window. You’ll see it again and again.
Second, you create your window on the screen, using the line of code that was there when you started. Making the window key means it’s now the prime recipient of user input (for what that’s worth in this simple example), whereas making it visible means that the user can see it.
Third, do you remember the standard rule that you must release anything you allocated? Here, that’s the label.
And that’s a simple Hello, World! program, completely programmed and working, with some neat graphical nuances.
Although it was sufficient for this purpose, Hello, World! didn’t make much use of the class creation that’s possible in an object-oriented language. Sure, you depended on some existing classes—including UIColor, UILabel, and UIWindow—but all of your new code went into a single function, and you didn’t create any classes of your own. We’ll address this issue in section 3.4, when you start working with new classes.
Creating a project for the iPad is almost identical to creating one for the iPhone. The main difference is that the window is much larger. You must also create slightly different files when starting the new project.
To begin, open Xcode, and select File > New Project. Next, select Window-Based Application. To denote that you want to start an iPad project, select iPad from the Product drop-down menu. Name the project HelloiPad.
We won’t cover the files in detail as we did for the iPhone template in section 3.2, because they’re almost the same. As mentioned earlier, the primary difference is the size of the main window. We’ll discuss the iPad interface further in chapter 7.
For this example, writing Hello, World! on the screen uses the exact same code you use for the iPhone. As you did in the previous example, open HelloiPadAppDelegate.m and add the code from listing 3.1 to the applicationDidFinishLaunching: method. Figure 3.3 shows how the Hello, World! application will look in the iPad Simulator.
As you can see, it looks identical to the iPhone Hello, World! app, with the exception of a larger screen. Because the iPhone and iPad are so similar, this is the last time we demonstrate an example on both platforms. Throughout the book, we’ll show examples using the iPhone while pointing out iPad-specific content along the way.
Now that you’ve built your first application, it’s time to make some improvements to it. In the next section, you’ll see how to expand Hello, World! and create a simple web browser.
New programs are usually full of new classes. Here are three major reasons you may want to create new classes:
Creating a new class and linking it in is easier than you think. In the next example, you’ll create a project called newclass that will include the brand-new labeledwebview subclass. Again, you’ll build it using the Window-Based Application template.
When you’ve got your new project going, the process of creating a new class (see table 3.2) is simple, with Xcode (as usual) doing most of the work for you in file creation.
Step |
Description |
---|---|
|
Choose File > New File. Choose the class to use as your parent from among the Cocoa Touch Classes options. Select your filename, preferably an intuitive name reflecting your object. Accept the default setup, including the creation of a .h file. |
|
If you weren’t able to select your preferred class to subclass, change that now by modifying the parent class in the @interface line of yourclass.h. |
|
Add an #import line for your class’s header in whatever file will be using it. |
For the sample web browser program, you create the Labeledwebview class as a subclass of UIView and then import your new Labeledwebview.h file into your application delegate’s .m file. To do this, choose File > New File. Then, click Objective-C Class. Select UIView from the Subclass drop-down menu, and click Next. Name the file Labeledwebview.m, and import it into your delegate like this:
#import "Labeledwebview.m"
Afterward, it’s a simple matter of designing your class to do the right thing. For this purpose, you’ll create an object that will display both a web page and the URL of that web page on the iPhone screen by linking together some existing classes. It will also display an address bar at the top, where the user can type in a URL to navigate to.
The process has three steps, all of which we touch on in this section: you need to write your new header file, write your new source code file, and use the new class in your program.
As usual, you have the start of a header file already, thanks to Xcode. Listing 3.2 shows how to expand it to create your new class.
#import <UIKit/UIKit.h>
@interface labeledwebview : UIView<UITextFieldDelegate>{
UIWebView *myWebView;
UIToolbar *toolbar;
UITextField *addressField;
UIBarItem *backButton;
}
@property(nonatomic, retain) UIWebView *myWebView;
@property(nonatomic, retain) UIToolbar *toolbar;
@property(nonatomic, retain) UITextField *addressField;
- (void)loadURL:(NSString *)url;
@end
This is the last time we look at a header file that contains only basic information in it; but because it’s your first time working with a new class, it’s worthwhile. Within the header file, you again engage in some of those common declarations that you saw back in your Hello, World! program.
First, you declare some instance variables that you want to use throughout your class. Second, you define those variables as properties. And third, you declare a method that you want to make available outside the class. Now you’re ready for the code.
The source code file contains the guts of your new class, as shown in listing 3.3.
Figure 3.4 shows the results of your class creation in use. We also explain the parts of the code that get you there, before we put it all together in the app delegate.
You always have to import your header file into its matched source code file. You follow that up by synthesizing your two properties, making them available for use.
You put together the pieces of your new class in the initWithFrame: method. As usual, you called your parent’s init. Then, you create the two objects your new class will contain: a label and a web view . After setting some basic values for each, you make them sub-views of your new labeledwebview class.
Don’t worry about the fact that we’re not spending much time on how the web view works; it’s one of the UIKit objects that will get more attention down the road, when we talk about the SDK and the web in chapter 14.
Because you set the delegate of the text field to Labeledwebview class, the code in is called when the user presses the Return key on their keyboard. This code tells the web view to load the web page address that the user typed in.
The real magic occurs in the brand-new loadURL: method . First, you load the URL in the web view. This requires a two-step process that goes through the NSURLRequest and NSURL class objects. (You can find more information in the Apple class references and in chapter 14.) That’s all you have to do to generate a fully functional web page, which is pretty amazing. If you try to use it, you’ll even find that it has much of the iPhone’s unique output functionality: you can pinch, tap, and zoom just like in Safari. You finish the method by setting the label to match your URL.
Your new class ends with the standard dealloc method, where you clean up the objects that you allocated as part of your object creation.
In less than a page of code, you create an object that would require a lot more work if you were programming it by hand. So many tools are available to you in the SDK that knocking out something like this is, as you can see, simplicity itself. You could definitely improve this example: you could link in to the UIWebViewDelegate protocol to update the label whenever the web view changed; but for now, we’re pleased with this second example of Xcoding.
Creating a new class isn’t enough: you also need to use it. Put the following code in the application delegate to use your new subclass:
#import "labeledwebview.h"
- (void)applicationDidFinishLaunching:(UIApplication *)application {
labeledwebview *myWeb = [[labeledwebview alloc]
initWithFrame:[[UIScreen mainScreen] bounds]];
[myWeb loadURL:@"http://www.manning.com/callen/"];
[myWeb setBackgroundColor:[UIColor grayColor]];
[window addSubview:myWeb];
[window makeKeyAndVisible];
}
As you can see, you create your new object as you would any object that comes naturally in the iPhone’s frameworks, and then you take advantage of those methods you coded into it.
You’ve now seen how to use Xcode to write a few simple programs. Before we finish this chapter, let’s take a quick look at some of Xcode’s other features, which you’ll doubtless be taking advantage of.
What follows are some notes on how to undertake other common Xcode tasks, ending with an overview of a lot of Xcode’s cooler bells and whistles that you may not be familiar with.
To date, your programs have included three frameworks: Core Graphics, Foundation, and UIKit. You may find someday that you want to add another framework, to get access to another set of classes that will make your life easier. In particular, if you have problems accessing a method defined in the SDK, you can look in the appropriate class reference and see the framework that’s required near the top of the reference.
All you have to do to add a framework to Xcode is Ctrl-click the Frameworks folder in your Xcode side pane and choose Add > Existing Frameworks. Xcode will show you a long list of frameworks. When you choose one, it’s automatically set up as a target when you compile.
Your default frameworks are selected by the template that you choose to use when you create your project. For example, the Window-Based Application determines that you have access to the Core Graphics, Foundation, and UIKit frameworks at the start. Other templates may give access to other frameworks with no additional work required on your part.
When you’re creating a new program in Xcode, you always have the option to select among several templates, each of which gives you a different basis for your code. Besides a Window-Based Application, you can create a project as a View-Based Application, a Tab Bar Application, a Navigation-Based Application, a Utility Application, or an OpenGL ES Application.
Most of these templates build in view controllers and give access to other functionality that you won’t encounter for a couple of chapters. We give you a glance at them all now so you can see the possibilities that Xcode offers. Figure 3.5 shows how much different templates can vary from the Window-Based Application that you’ve been using.
Here’s a bit more information about each of the six templates:
Before we leave Xcode behind, let’s explore a few of the great features it includes to make your coding easier. You can investigate these features in any of the projects that you’ve written so far.
You see a file’s code in an editing window whenever you single-click a .h or .m file. If this window isn’t big enough, you can instead double-click to get a brand-new window.
The editing window includes a number of nice features:
You call up this window by choosing Window > Organizer. You can store references to a number of projects here, linking them in from the + menu that appears at the bottom of the window. In addition to easily accessing your projects, you can compile them in a variety of configurations and even see debugging logs and crash logs related to them.
Xcode is ultimately the basis of all SDK programming. It’s where you write the code that allows you to create, manipulate, and destroy objects. As you’ve seen in this chapter, it’s easy to use Xcode to do pretty sophisticated things. This is in part due to Objective-C’s elegant methods of messaging and in part due to the iPhone OS’s massive library of classes.
But there’s another way to do things. You can also create basic user interface objects visually, using Interface Builder. It allows you to lay out objects using a graphical UI that makes their arrangement a lot easier. That will be the basis of the next chapter, when we delve into the other side of SDK programming.