Chapter 2. Understanding Basic Syntax

In This Chapter

  • Writing your first program

  • Declaring variables

  • Working with functions

  • Using flow control statements

  • Using loops

In this chapter, I show you how to write a basic Objective-C program. This very simple command line application will print a short message to the console. Using this basic program, you will explore some of the essentials of Objective-C, beginning first with how to actually write the code, moving into working with variables and functions, and finally, controlling the flow of your program by using conditional statements and loops. These concepts are fundamental to learning the language, and you should study this chapter thoroughly before moving on to the next one.

Go ahead and type in the code from Listing 2.1 into the Xcode project you created in Chapter 1. This code should be entered into the source file which is named after your project name, located in the Source group.

Example 2.1. Your first program

#import <Foundation/Foundation.h>

int main(int argc, const char *argv[])
{
    NSLog(@"Hello from Objective-C");
    return 0;
}

I'm going to jump around in this code a bit because it makes it easier to explain that way.

Start with line 3, which is the declaration of the main function. All Objective-C applications have a main function. Typically you don't see it because it's usually created by your template when you create your project; when working with graphical applications, it's rare that you have to edit this code at all. I want to ...

Get Objective-C now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.