Objective-C Lesson 1: Hello World!


Note: Click on any image to see a larger version.

Since Dennis Ritchie demoed the C programming language, it has been conventional to begin a programming course with a program that writes the words “Hello world!” to the computer screen. Diving right in, the code is shown below.

Program 1.1

// First program example

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        NSLog (@"Hello, World!");
        [pool drain];
        return 0;
}

Using Xcode

So what does all this gibberish mean? Before we can get to that, we’ll run the program first.

Download a copy of Xcode, if you don’t have it already, and install it. Navigation to your boot drive (usually Macintosh HD), and the folder called Developer. Inside, there will be a folder called Applications. Xcode, and some other programs you will be using, is in there.

Xcode is located at /Developer/Applications

Location of Xcode.app

Drag it to your dock, or create an alias for it in your Applications folder. Launch Xcode. The first thing you’ll see is the launch window:

Xcode Launch Window (With Highlighting)

Xcode Launch Window (New Project Highligted)

Click on “Create a new Xcode project,” or select File > New Project (⇧⌘N). The button is highlighted in the image above. You will be greeted by the following window:

Xcode's New Image Window

Xcode's New Image Window

Select Application under Mac OS X on the left, and choose Command Line Tool on the right. Make sure the Type drop-down menu in the middle is set to Foundation. Click Choose…

Name your project, and save it somewhere on your hard drive. In a few moments, you’ll see Xcode’s main interface:

Xcode

Xcode's Main Window

We’ll take more about the parts of the window in later sections. Click on the file called Hello World.m, or something similar. This should bring up the editor window. Replace the code in the editor view with the code above, so that it looks like this:

Hello, World entered in Xcode

The Code in Xcode's Editor

Don’t worry about all the colors—we’ll discuss that later. When you have entered the code, save the file, and click the “Build and Run” or “Build and Go” button in the toolbar.

If you’ve made a mistake when typing it in, the toolbar at the bottom of Xcode’s window will change, and a message bubble will appear:

Xcode tells you when you've made a mistake

Xcode Tells You About Errors

Go back, and check the code.

When everything is working, you’ll see yet another window:

Xcode Displays the Result of the Code in the Console

Xcode Displays the Result of the Program

The output is as follows:

2010-09-03 10:47:32.414 Hello World[25379:a0f] Hello, World!

The beginning of the line shows the date and time, followed by the name of the program, and bunch of gibberish. But at the end of the line is the text that you expected to see: The program has written the words “Hello, World!” onto the screen.

Throughout the rest of these tutorials, the text that appears before that actual text that is outputted will be omitted for brevity.

Code, Demystified

Now that you’ve created a working program, let’s talk about how it works.

In Objective-C, a capital and lowercase letter mean different things. So, main, Main, and mAin are three completely different things, and cannot be used interchangeably. Also note that white space—spaces, tabs, and blank lines are ignored. You can use this to format your code properly. Take advantage of this freedom to properly format your code.

The first line of the program is a comment:

// First program example

Comments exist solely for the benefit of the programmer. Comments are important, because they allow the developer to explain a thought process. They help demystify the code, and make documenting the code sometime down the road easier. Comments help during the debugging process, or when you revisit your code some time later. It also helps other people who may use your code understand why things are the way the are. The compiler ignores comments, so you can type anything into a comment.

There are two types of comments in Objective-C. One is shown above, in which every line of the comment is preceded by two slashes. This type of comment ends at the end of the line.

A comment can also be written across multiple lines, with the following syntax:

/*
A multi-line comment can be inserted
by using a slash
and then an asterisk.
The comment can be as long as you want,
but make sure you close it
with an asterisk, then a slash. */

Which style you choose is a matter of preference, or as the situation dictates.

The next line of the program imports, or brings into your project, a file called Foundation.h:

#import <Foundation/Foundation.h>

The file in question is a system file, and that is why the name is enclosed in the brackets < and >. If you were importing a local file , you would enclose the file name in double quotes “ and ”.  This file is imported because code later in the file requires information that is contained in this file;  you are telling the compiler to look up the information in that file as necessary.

The following line declares a function called main:

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

main is a function that is where every C or C-based program begins. It is a reserved name, which means that you can’t have a function named main. The word int that precedes main is a declaration of the return type of the function. These topics will be discussed in further chapters.

After identifying main to the compiler, you tell the system what to do when it is called. These statements are enclosed in the braces { and } that surround the next few lines. Every opening brace has to be matched with a closing brace.

The first statement in main is as follows:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

This involves memory management, which is a topic thoroughly discussed in upcoming chapters.

The next line calls NSLog, which, along with the NSAutoreleasePool from above, is a function brought in by Foundation.h, which you imported.

NSLog (@"Hello, World!");

This line tells the function NSLog, which is designed to output text, to print the characters Hello, World! on the screen.

The leading @ in front of the string signifies to the compiler that this is an NSString (another object brought in from the Foundation.h file), not a C-style string. For the most part, you will be using NSStrings, rather than C-style strings.

All statements, or lines that indicate some action, must be terminated with a semicolon ; just like regular sentences are terminated with a period.

The next line is part of the NSAutoreleasePool, and its purpose and meaning will be discussed in a later chapter.
The final line tells the main method to return the value 0. Remember that the int the preceded main tells the system that this function will return a value. This value is 0. By convention, a return value of zero indicates that the function was successful.

return 0;

This line is followed by a closing brace, signifying the end of the main function.

If you look back at the window that displays the output of your program, you should see the line

Program exited with status value:0.

This is an indication of the return value of main.

Congratulations, you have created your first program in Objective-C!

Leave a comment

12 Comments

  1. toon

     /  March 18, 2012

    When I repeat the steps described, and build and run the code, I get 20 errors… I use Xcode 4.1. What can be wrong? My NSAutoreleasePool is also just black, not purple-colored.

    Also, good job on the website! Hope it will get me started working with Xcode!

    Reply
    • What Xcode template did you use? In Xcode 4.1, you should be under Mac OS X > Application > Command Line Tool.

      Xcode 4: Command-Line Tool

      Make sure you’re putting the code in main(). What are some of the errors you’re getting?

      Reply
  2. When you are creating the file, after you select command line tool, you will be brought to a window where you name your project, etc. There you must uncheck the checkbox below that info. It says something about a reference. It should then work.

    My output in Hello World is a little different so I am still having issues….as usual in these annoying tutorials

    Reply
    • What output are you getting? The NSLog function has been tweaked across versions. The stuff before “Hello world” could quite possibly have changed; that’s on Apple’s side.

      Reply
  3. 2012-08-28 21:56:38.538 Hello World[2598:403] Hello, World!
    2012-08-28 21:56:38.540 Hello World[2598:403] I’m ready to program in Objective-C!

    Oh and I didnt mean your tutorial is bad, I just meant as the versions of everything advances everything taught from a past version of a program is messed up (in most tutorials found)…haha i think it came out wrong in my last comment…oops sorry 🙂

    Reply
    • It’s okay, I know what you mean. Most of the time though the calls and end results are the same. It’s like the black box bit—Apple can change and tweak stuff on their end, but the bits that are relevant to you usually stay the same.

      Reply
  4. Andreé Canelas

     /  July 13, 2013

    is there anyway you can reupload your images? Im am really interested on following your tutorial, thanks in advance.

    Reply
  1. Extending “Hello, World!” « Programming for iOS
  2. Learn Objective-C in 24 Days « Programming for iOS
  3. Creating a New iPhone Project « Programming for iOS
  4. 2010 in review « Programming for iOS
  5. ‘The Most Popular New Version of An OS In History’ | Statspotting!

Leave a comment

  • Welcome

    My goal is to make CupsOfCocoa into a beautiful source for beginners to the iPhone platform to get started. Subscribe below for more, and stay tuned!

  • Contact Me

    If you need to contact me for any reason, feel free to send me an email.
  • The Giving Spirit

    If you've found this site helpful, would you consider donating a little sum? Any amount is appreciated...Thanks so much!

  • Roadmap

  • Enter your email address to follow this blog and receive notifications of new posts by email.

    Join 217 other subscribers
  • Back to the Past

    September 2010
    S M T W T F S
     1234
    567891011
    12131415161718
    19202122232425
    2627282930  
  • Time Machine

  • You count!

    • 625,601 views
  • Worldwide Stats

    free counters