2. Programming in Objective-C

In this chapter we'll dive right in and show you how to write your first Objective-C program. You won't work with objects just yet; that is the topic of the next chapter. We want you to understand the steps involved in keying in a program and compiling and running it. Special attention is given to this process under Windows and on a Macintosh computer.

To begin, let's pick a rather simple example—a program that displays the phrase Programming is fun. on your screen. Without further ado, here is an Objective-C program to accomplish this task.

Program 2.1.


// First program example
#import <stdio.h>

int main (int argc, const char *argv[])
{
  printf ("Programming is fun. ");

  return 0;
}


Before we go into a detailed explanation of this program, let's learn the steps involved in compiling and running it. You first need to enter the lines from Program 2.1 into a text file. Then, you need to issue the right commands to compile and execute it. Let's examine how to go about doing that in detail.

Compiling and Running Programs on the Mac

If you're using Mac OS X, you have two choices. You can either compile and run your program using the GNU Objective-C compiler in a Terminal window, or you can use Project Builder1. Let's go through the sequence of steps using either method. Then, you can decide how you want to work with your programs throughout the rest of this book.

Compiling Programs in a Terminal Window

The first step is to start the Terminal application on your Mac. The Terminal application is located in the Applications folder, stored under Utilities. Its icon is shown in Figure 2.1.

Figure 2.1. Terminal program icon.

image

Start the Terminal application, and you'll see a window that looks like Figure 2.2.

Figure 2.2. Terminal window.

image

Commands are typed after the $ (or % depending on how your Terminal application is configured) on each line. If you're familiar with using Unix, this will be straightforward.

First, you need to enter the lines from Program 2.1 into a file. You can begin by creating a directory in which to store your program examples. Then, you must run a text editor, such as vi or emacs, to enter your program:

sh-2.05a$ mkdir MySrc   Create a directory to store programs in
sh-2.05a$ cd MySrc      Change to the new directory
sh-2.05a$ vi main.m     Start up a text editor to enter program
..

In the previous example and throughout the remainder of this text, commands entered by you, the user, are indicated in boldface.

For Objective-C files, you can choose any name you want; just make sure the last two characters are .m. This is done out of convention, so that the compiler knows you have an Objective-C program. Other commonly used filename suffixes are shown in Table 2.1.

Table 2.1. Common Filename Suffixes

image

After you've entered your program into a file, you can use the GNU Objective-C compiler, which is called gcc, to compile and link your program. The general format of the gcc command is

gcc files -o progname -l objc

Here, files is the list of files to be compiled. In our example, we have only one such file and we're calling it main.m. progname is the name of the file that will contain the executable if the program compiles without any errors. The rest of the line contains information about linking your program. The option

-l objc

says to link with the Objective-C runtime library called objc. Just remember to use this option at the end of each line.

Let's call the program prog1; here then is the command line to compile your first Objective-C program:

sh-2.05a$ gcc main.m -o prog1 -l objc  Compile main.m & call it prog1
sh-2.05a$

The return of the command prompt without any messages means that no errors were found in the program. Now you can subsequently execute the program by typing the name prog1 at the command prompt:

sh-2.05a$ prog1        Execute prog1
sh: prog1: command not found
sh-2.05a$

This is the result you'll probably get unless you've used Terminal before. The fact is that the Unix shell (which is the application running your program) doesn't know where prog1 is located. We won't get into all the details here. You have two options: One is to precede the name of the program with the characters ./ so that the shell knows to look in the current directory for the program to execute. The other is to add the directory in which your programs are stored (or just simply the current directory) to your PATH variable. Ask someone for help on how to do this if needed.

Let's take the first approach here:

sh-2.05a$ ./prog1      Execute prog1
Programming is fun.
sh-2.05a$

That's better! If you used Terminal to compile and execute your program, you can skip the next section. However, you might want to skim this section to learn how you can also use Project Builder to compile and run your programs.

Compiling and Running Programs Using Project Builder

Project Builder is a sophisticated application that allows you to easily type in, compile, debug, and execute programs. If you plan on doing serious application development on the Mac, learning how to use this powerful tool is worthwhile. We'll just get you started here. Later, we'll return to Project Builder and take you through the steps involved in developing a graphical application with it.


Note

As of the writing of this book, Apple was in the process of replacing Project Builder with an improved tool called Xcode. Notable interface differences do exist, but Xcode behaves very similarly and these instructions should work fine. That said, any big discrepancies will be pointed out.


First, Project Builder is located in the Developer folder inside a subfolder called Applications. Its icon is shown in Figure 2.3.

Figure 2.3. Project Builder icon.

image

Start Project Builder. Under the File menu, select New Project (see Figure 2.4).

Figure 2.4. Starting a new project.

image

A window will then appear, as shown in Figure 2.5.

Figure 2.5. Starting a new project (cont'd).

image

Unfortunately, there is no project type that you can select here that describes precisely what you want to do, so select Cocoa Application. After highlighting Cocoa Application, click Next. This brings up a new window shown in Figure 2.6.

Figure 2.6. Starting a new project (cont'd).

image

Let's call the first program prog1, so type that into the Project Name field. For the Location field, you can let the Mac choose where to store your project files, or you can type in a directory. By default, it stores the project in the directory ~/prog1/, where the Unix notation ~ is used to specify the name of your Home directory.

The Next button changes to Finish; clicking it causes the Location field to be filled in, if you didn't fill it in yourself. It then closes the Assistant window, replacing it with the window that appears in Figure 2.7.

Figure 2.7. Project Builder file list window.

image

Now it's time to type in your first program, so under prog1 in the left side of the window, click Other Sources. This reveals the file main.m, as shown in Figure 2.8.

Figure 2.8. main.m file.

image

Highlight the file main.m. Your Project Builder window should now appear as shown in Figure 2.9.

Figure 2.9. File main.m and edit window.

image

The right side of the window shows the file called main.m and contains the following lines:

//
// main.m
// prog1
//
// Created by Steve Kochan on Mon Aug 25 2003.
// Copyright (c) 2003 __MyCompanyName__. All rights reserved.
//

#import <Cocoa/Cocoa.h>

int main(int argc, const char *argv[])
{
  return NSApplicationMain(argc, argv);
}

You can edit your file inside this window. Project Builder has created a template file for you to use. Unfortunately, it's a little more than you need right now. Therefore, remove a couple of lines and continue. To make main.m look more like your first program, replace the line

#import <Cocoa/Cocoa.h>

with the line

#import <stdio.h>

and replace the line that reads

return NSApplicationMain(argc, argv);

with

return 0;

You can leave all the lines at the beginning of main.m that start with two slash characters (//). Those lines are comments, and we'll talk more about them shortly.

Your program in the edit window should now look like this:

//
// main.m
// prog1
//
// Created by Steve Kochan on Mon Aug 25 2003.
// Copyright (c) 2003 __MyCompanyName__. All rights reserved.
//

#import <stdio.h>

int main (int argc, const char *argv[])
{
  printf ("Programming is fun. ");
  return 0;
}

Don't worry about all the colors shown for your text on your screen. Project Builder indicates values, reserved words, and so on using different colors.

Now it's time to compile and run your first program—in Project Builder terminology it's called build and run. You need to save your program first, however. This can be done by selecting Save from the File menu. If you try to compile and run your program without first saving your file, Project Builder asks whether you want to first save your program.

Under the Build menu, you can select either Build or Build and Run. Select the latter because that automatically runs the program if it builds without any errors. You can also activate Build and Run by clicking the image icon that appears in the toolbar.

A window labeled Build: prog1 - (prog1) appears first and details the build process. You'll see several text lines scrolling quickly through a small section of the window in the middle. Those are the actual command lines that are being executed to build your program example. In fact, Project Builder uses the same gcc compiler you used in the Terminal application window in the previous section.

If you made mistakes in your program, you'll see error messages listed during this step. In that case, go back, fix the errors, and repeat the process. After all the errors have been removed from the program, a new window appears; it's labeled Run: prog1 - (prog1). This window contains the output from your program and should look similar to Figure 2.10. If this window does not automatically appear, go to the main menu bar and select Show Run Log from the Debug menu.

Figure 2.10. Project Builder Run window.

image

You're now done with the procedural part of compiling and running your first program with Project Builder (whew!). The following summarizes the steps involved in creating a new program with Project Builder:

  1. Start the Project Builder application
  2. If this is a new project, select File, New Project.
  3. For the type of application, select Cocoa Application and click Next.
  4. Select a name for your project, and optionally a directory to store your project files in. Click Finish.
  5. Under Other Sources you will see the file main.m. Highlight that file. Type your program into the edit window on the right side of the screen.
  6. Save the changes you've entered by selecting File, Save.
  7. Build and run your application by selecting Build, Build and Run.
  8. If you get any compiler errors or the output is not what you expected, make your changes to the program and repeat steps 6 and 7.

Compiling and Running Programs under Windows

If you're running Windows, you can download an Objective-C compiler that is part of the MinGW system from http://www.mingw.org, get an Objective-C compiler that runs under CygWin (http://www.cygwin.com/)2, or ask your system administrator to locate or install a compiler for you.

Using the Objective-C compiler from MinGW is a good choice because the Objective-C compiler runs without any special software in a DOS-box under Windows. We'll go through the steps involved in compiling and running an Objective-C program under that environment. These steps are virtually identical to those outlined for compiling Objective-C programs using Terminal on the Mac.

We'll assume you have installed the MinGW system. Start the MS-DOS Prompt utility. You should see a window similar to Figure 2.11.

Figure 2.11. MS-DOS window.

image

(What appears on your window might appear slightly different, depending on which version of Windows you're running, for example.) You have to find where your Objective-C compiler is located. If you followed the standard installation procedures, it's located in the directory C:MinGWin. To have the system find the Objective-C compiler (the next time you boot your system), you should add this directory to your PATH in your autoexec.bat file. You should add a line that looks something like this:

SET PATH=%PATH%;C:MINGWBIN

To type in your first program, you can use any editor you like; the built-in Windows editor edit will work just fine. Let's assume you have typed Program 2.1 into a file called main.m in a directory on your C: drive called mysrc. You can now use the Objective-C compiler that comes with MinGW to compile and link your program. The general format of the command to do this is

gcc files -o progname -l objc

where files is the list of files to be compiled. In this example, you have only one such file, called main.m. progname is the name of the file that will contain the executable program if the compiler detects no errors. The rest of the line contains information about linking your program. The option

-l objc

says to link with the Objective-C runtime library called objc. Just remember to use this option at the end of each line.

If you call your program prog1, the command line to compile your first Objective-C program would be as follows:

C:mysrc> gcc main.m -o prog1 -l objc   Compile main.m call it prog1
main.m:1:2: warning: #import is obsolete, use an #ifndef wrapper in the header
file
C:mysrc>

In the previous example and throughout the remainder of this text, the commands entered by the user are indicated in boldface.

The compiler issues a warning message that has to do with the #import statement that appears in the program. You should ignore this message.

The return of the command prompt after the warning message means that no errors were found in the program. You can subsequently execute the program by typing the name prog1 at the command prompt, like so:

C:mysrc> prog1          Execute prog1
Programming is fun.      Program output
C:mysrc>

Line-by-Line Explanation of Your First Program

Now that you are familiar with the steps involved in compiling and running Objective-C programs, let's take a closer look at this first program. Here it is again.

Program 2.1.


// First program example
#import <stdio.h>

int main (int argc, const char *argv[])
{
  printf ("Programming is fun. ");
  return 0;
}


In Objective-C, lowercase and uppercase letters are distinct. Also, Objective-C does not care where on the line you begin typing—you can begin typing your statement at any position on the line. This fact can be used to your advantage in developing programs that are easier to read.

Comments

The first line of the program

// First program example

introduces the concept of the comment. A comment statement is used in a program to document a program and enhance its readability. Comments serve to tell the reader of the program—be it the programmer or someone else whose responsibility it is to maintain the program—just what the programmer had in mind when she wrote a particular program or a particular sequence of statements.

You can insert comments into an Objective-C program in two ways. One is by using two consecutive slash characters (//). Any characters that follow these slashes up to the end of the line are ignored by the compiler.

A comment can also be initiated by the two characters / and *. This marks the beginning of the comment, and these types of comments have to be terminated. To end the comment, the characters * and / are used, once again without any embedded spaces. All characters included between the opening /* and the closing */ are treated as part of the comment statement and are ignored by the Objective-C compiler. This form of comment is often used when comments span many lines of code, such as in the following:

/*
  This file implements a class called Fraction, which
  represents fractional numbers. Methods allow manipulation of
  fractions, such as addition, subtraction, etc.

  For more information, consult the document:
    /usr/docs/classes/fractions.pdf
*/

Which style of comment you use is entirely up to you. Just note that you can't nest the /* style comments.

You should get into the habit of inserting comment statements in the program as the program is being written or typed into the computer. There are three good reasons for this. First, documenting the program while the particular program logic is still fresh in your mind is far easier than going back and rethinking the logic after the program has been completed. Second, by inserting comments into the program at such an early stage of the game, you can reap the benefits of the comments during the debug phase, when program logic errors are isolated and debugged. A comment can not only help you (and others) read through the program, but can also help point the way to the source of the logic mistake. Finally, I have yet to discover a programmer who actually enjoys documenting a program. In fact, after you have finished debugging your program, you will probably not relish the idea of going back to the program to insert comments. Inserting comments while developing the program makes this sometimes tedious task a bit easier to handle.

The next line of Program 2.1 that reads

#import <stdio.h>

tells the compiler to locate and process a file named stdio.h, which is a system file—that is, not a file you created. #import says to import or include the information from that file into the program, exactly as if the contents of the file were typed into the program at that point. You imported the file stdio.h because it has information about the printf output routine used later in the program.

In Program 2.1, the line that reads

int main (int argc, const char *argv[])

specifies that the name of the program is main, which is a special name that indicates precisely where the program is to begin execution. The reserved word int that precedes main specifies the type of value main returns, which is an integer (more about that soon). We will ignore what appears between the open and closed parentheses for now. These have to do with what are known as command-line arguments, a topic we address in Chapter 13, “Underlying C Language Features.”

Now that you have identified main to the system, you are ready to specify precisely what this routine is to perform. This is done by enclosing all the program statements of the routine within a pair of curly braces. In the simplest case, a statement is just an expression that is terminated with a semicolon. All the program statements included between the braces will be taken as part of the main routine by the system. Program 2.1 has two statements. The first statement specifies that a routine named printf is to be invoked, or called. The parameter, or argument, to be passed or handed to the printf routine is the following string of characters:

"Programming is fun. "

The printf routine is a function in the Objective-C library that simply prints or displays its argument (or arguments, as you will see shortly) on the screen. The last two characters in the string, namely the backslash () and the letter n, are known collectively as the newline character. A newline character tells the system to do precisely what its name implies—go to a new line. Any characters to be printed after the newline character then appear on the next line of the terminal or display. In fact, the newline character is very similar in concept to the carriage return key on a typewriter.

All program statements in Objective-C must be terminated by a semicolon (;). This is why a semicolon appears immediately following the closed parenthesis of the printf call.

The second program statement in main

return 0;

says to terminate execution of main and to send back, or return, a status value of 0. By convention, 0 means that the program ended normally. Any nonzero value typically means some problem occurred—for example perhaps a file that was needed by the program couldn't be located.

If you're using Project Builder and you glance back to your Run window (refer to Figure 2.10), you'll recall that after the line of output from printf, the following was displayed:

prog1 has exited with status 0.

You should understand what that message means now.

Now that we have finished discussing your first program, let's modify it to also display the phrase “And programming in Objective-C is even more fun.” This can be done by simply adding another call to the printf routine, as shown in Program 2.2. Remember that every Objective-C program statement must be terminated by a semicolon.

Program 2.2.


#import <stdio.h>

int main (int argc, const char *argv[])
{
  printf ("Programming is fun. ");
  printf ("Programming in Objective-C is even more fun. ");

  return 0;
}


If you type in Program 2.2 and then compile and execute it, you can expect the following output at your terminal.

Program 2.2. Output


Programming is fun.
Programming in Objective-C is even more fun.


As you will see from the next program example, you don't need to make a separate call to the printf routine for each line of output. Study the program listed in Program 2.3 and try to predict the results before examining the output (no cheating, now!).

Program 2.3.


#import <stdio.h>

int main (int argc, const char *argv[])
{
  printf ("Testing... ..1 ...2 ....3 ");
  return 0;
}


Program 2.3. Output


Testing...
..1
...2
....3


Displaying the Values of Variables

Not only can simple phrases be displayed with printf, but the values of variables and the results of computations can be displayed as well. Program 2.4 uses the printf routine to display the results of adding two numbers, namely 50 and 25.

Program 2.4.


#import <stdio.h>

int main (int argc, const char *argv[])
{
  int sum;

  sum = 50 + 25;
  printf ("The sum of 50 and 25 is %i ", sum);
  return 0;
}


Program 2.4. Output


The sum of 50 and 25 is 75


The first program statement inside main defines the variable sum to be of type integer. All program variables must be defined before they are used in a program. The definition of a variable specifies to the Objective-C compiler how it will be used by the program. This information is needed by the compiler to generate the correct instructions to store and retrieve values into and out of the variable. A variable defined as type int can be used to hold only integral values—that is, values without decimal places. Examples of integral values are 3, 5, –20, and 0. Numbers with decimal places, such as 2.14, 2.455, and 27.0, are known as floating point numbers and are real numbers.

The integer variable sum is used to store the result of the addition of the two integers 50 and 25. We have intentionally left a blank line following the definition of this variable to visually separate the variable declarations of the routine from the program statements; this is strictly a matter of style. Sometimes the addition of a single blank line in a program can help make the program more readable.

The program statement

sum = 50 + 25;

reads as it would in most other programming languages: The number 50 is added (as indicated by the plus sign) to the number 25, and the result is stored (as indicated by the assignment operator, the equal sign) into the variable sum.

The printf routine call in Program 2.4 now has two arguments enclosed within the parentheses. These arguments are separated by a comma. The first argument to the printf routine is always the character string to be displayed. However, along with the display of the character string, you often might want to have the value of certain program variables displayed as well. In this case, you want to have the value of the variable sum displayed at the terminal after the characters are displayed:

The sum of 50 and 25 is

The percent character inside the first argument is a special character recognized by the printf function. The character that immediately follows the percent sign specifies what type of value is to be displayed at that point. In the previous program, the letter i is recognized by the printf routine as signifying that an integer value is to be displayed.

Whenever the printf routine finds the %i characters inside a character string, it automatically displays the value of the next argument to the routine. Because sum is the next argument to printf, its value is automatically displayed after the characters The sum of 50 and 25 is are displayed.

Now try to predict the output from Program 2.5.

Program 2.5.


#import <stdio.h>

int main (int argc, const char *argv[])
{
  int value1, value2, sum;

  value1 = 50;
  value2 = 25;
  sum = value1 + value2;

  printf ("The sum of %i and %i is %i ", value1, value2, sum);

  return 0;
}


Program 2.5. Output


The sum of 50 and 25 is 75


The first program statement inside main defines three variables called value1, value2, and sum all to be of type int. This statement could have equivalently been expressed using three separate statements as follows:

int value1;
int value2;
int sum;

After the three variables have been defined, the program assigns the value 50 to the variable value1 and then the value 25 to value2. The sum of these two variables is then computed and the result assigned to the variable sum.

The call to the printf routine now contains four arguments. Once again, the first argument, commonly called the format string, describes to the system how the remaining arguments are to be displayed. The value of value1 is to be displayed immediately following the display of the characters The sum of are displayed. Similarly, the values of value2 and sum are to be printed at the appropriate points as indicated by the next two occurrences of the %i characters in the format string.

This discussion concludes this introductory chapter on developing programs in Objective-C. By now, you should have a good feel as to what is involved in writing a program in Objective-C, and you should be able to develop a small program on your own. In the next chapter, you will begin to examine some of the finer intricacies of this powerful and flexible programming language. But first, try your hand at the exercises that follow to make sure you understand the concepts presented in this chapter.

Exercises

  1. If you have access to an Objective-C compiler, type in and run the five programs presented in this chapter. Compare the output produced by each program with the output presented after each program.
  2. Write a program that displays the following text:

    In Objective-C, lowercase letters are significant.
    main is where program execution begins.
    Open and closed braces enclose program statements in a routine.
    All program statements must be terminated by a semicolon.

  3. What output would you expect from the following program?

    #import <stdio.h>

    int main (int argc, const char *argv[])
    {
      printf ("Testing...");
      printf ("....1");
      printf ("...2");
      printf ("..3");
      printf (" ");
      return 0;
    }

  4. Write a program that subtracts the value 15 from 87 and displays the result, together with an appropriate message.
  5. Identify the syntactic errors in the following program. Then type in and run the corrected program to make sure you have identified all the mistakes:

    #import <stdio.h>

    int main (int argc, const char *argv[]);
    (
      INT sum;
      /* COMPUTE RESULT //
      sum = 25 + 37 - 19
      / DISPLAY RESULTS /
      printf ('The answer is %i ' sum);

      return 0;
    }

  6. What output would you expect from the following program?

    #import <stdio.h>

    main (int argc, const char *argv[]))
    {
      int answer, result;

      answer = 100;
      result = answer - 10;

      printf ("The result is %i ", result + 5);

      return 0;
    }

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.34.154